Create your first widget in Yii2

In this tutorial i will show you how you can create own custom widget in Yii2.The main advantage of Widget is you can write once and reuse it wherever you need it in your view. Widgets are reusable blocks and they are used in your views. Create a custom widget we must extend the base widget yii\base\Widget and we have to override the init() or run() methods of base widget.

Yii2 Widget

Step 1: Create a folder named components or changed name in your project folder.

Step 2: Create a file with desired widget name inside components folder and paste the below code. Example – HelloWidget.php


namespace app\components;

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

class Hellowidget extends Widget

    public $msg;

    public function init()

        if ($this->msg === null) {
            $this->msg = 'Welcome Here';
        } else {
            $this->msg = 'Welcome ' . $this->msg;

    public function run()
        // you can load & return the view or you can return the output variable
        return $this->render('my-widge', ['message' => $this->msg]);

In HelloWidget is a class and we can access the widget like 'app\components\HelloWidget'.

Step 3: Create a view and put the content into it.

Step 4: Everything is can call now widget.

<?php echo \app\components\HelloWidget::widget() ?>

I hope you like the post. please share and comment.

No comments:

Post a Comment

Download the eBook of react js for beginners

ReactJS basically is an open-source JavaScript library which is used for building user interfaces specifically for single page applications...