arrow_back
Back

Yii2 widgets: configuration, rendering, and built-in widgets

Andrew Dorokhov Andrew Dorokhov schedule 1 min read

Yii2 is a framework with an MVC architecture. Logic, views and controllers are separated here. Widget is a component that directly relates to the view component.

Widget example:

namespace app\widgets;

use yii\base\Widget;
use yii\helpers\Html;

class HelloWidget extends Widget
{
    public $message;

    public function init()
    {
        parent::init();
        if ($this->message === null) {
            $this->message = 'Hello World';
        }
    }

    public function run()
    {
        return Html::encode($this->message);
    }
}

To use this widget, simply insert the following code in a view:

<?php
use app\components\HelloWidget;
?>
<?= HelloWidget::widget(['message' => 'Good morning']) ?>
code

Need Help with Development?

Happy to help — reach out via the contacts or go straight to my Upwork profile.

work View Upwork Profile arrow_forward
Next Article

Yii2 admin section: folder structure and backend setup

arrow_forward