How you can create a new widget in Yii Framework 2

In this tutorial I'm going to explain to you how you can create your first widget in Yii Framework version 2.0. I have created also a video tutorial where you can see how the widget works.

I will follow this documentation to create a new widget in Yii Framework 2.0:

So, if you want to create a new widget:

  • Go to C:\xampp\htdocs\yii\vendor\yiisoft\yii2\widgets
  • Create a new file called HelloWidget with this code:

namespace yii\widgets;

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

class HelloWidget extends Widget
public $message;

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

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

  • Next, to your view folder and create a new file with this code:

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

Don't forget to create a new action in your Controller to call the new created view file!

Video tutorial:

Leave a Comment