Published on

How to create a custom widget in Yii2 Framework

Authors
  • avatar
    Name
    Bal Singh
    Twitter

Some time there is a need to reuse your logic and design. So to do this, widget is the best solution. Widgets are reusable building blocks. The main concept and advantage of widgets is that you can build your code once, and reuse it wherever you need it in your view.  Here I am going to describe the steps, how you can create simple MyWidget.

Step1

First create a folder named “components” in the project root directory. Create a MyWidget file and class in components folder. Override the int() and run() method of  Widget class as

<?php  
namespace app\components;  
  
use yii\base\Widget;  
use yii\helpers\Html;  
  
class RecentPostWidget extends Widget{  
    public function init(){  
            // add your logic here  
    }  
    public function run(){  
            return $this->render('myWidget');  
    }  
}  
?>

Step2

Create a views folder inside components  folder. Create a view file named myWidget.php in components/views folder and put your content in it.

Step3

Call to MyWidget class as

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

Exmaple: how you can create recent post widget.

Create your RecentPostWidget class in componets folder.

<?php  
namespace app\components;  
use yii\base\Widget;  
use yii\helpers\Html;  
  
class RecentPostWidget extends Widget{  
    public $limit=5;  
    public $posts;  
    public function init(){  
            parent::init();  
            $this->posts = \app\models\Post::find()->limit($this->limit)->all();  
    }  
      
    public function run(){  
            return $this->render('recentPostWidget',['posts'=>$this->posts]);  
    }  
}  
?>

Put the content into your recentPostWidget view file under componets/views folder.

<ul>  
      <?php foreach ($posts as $postData){ ?>  
      <li>  
           <?php echo $postData->title; ?>  
      </li>  
      <?php } ?>  
</ul>

Final step call to your RecentPostWidget

<?php echo \app\components\RecentPostWidget::widget(['limit' => 5]) ?>