How to create custom widget in Yii2.0 Framework

This tutorial will help you to create your own custom widget in yii framework 2.0. Widgets are reusable blocks and it is used in view.
To create a widget,
Extend from yii\base\Widget.
Override the yii\base\Widget::init() and/or yii\base\Widget::run() methods.

Note: In yii 1.x, we will use component folder.

Create Your Own Widget In Yii2.0

First create a folder named “components” in the project root directory. Now create one class ‘HelloWidget’ inside the components folder. Using this widget, we will show the welcome message with user name.
Please see the below code to create a widget class.

<?php
namespace app\components;

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= 'Welcome User';
		}else{
			$this->message= 'Welcome '.$this->message;
		}
	}
	
	public function run(){
		return Html::encode($this->message);
	}
}
?>
init() - should contain the widget properties,
run()  - should contain rendering result of the widget

In this class ‘HelloWidget’ is our custom widget. ‘app\components’ is the namespace of this class and ‘HelloWidget’ is a class name. Using both namespace and class name, we can access this widget like ‘app\components\HelloWidget’.

Display Your Widget Content In Yii2.0

To Use the widget just add the ‘app\components\HelloWidget’ namespace code in the view. See the below code How we called the widget class.

Controller: SiteController.php

<?php
..........
class SiteController  extends Controller
{
	...........
	public function actionCreatewidget(){
		return $this->render('hellowidget');
	}
	...........
}
?>

View: site/hellowidget.php

<?php
use app\components\HelloWidget;
?>
<?= HelloWidget2::widget(['message' => ' Yii2.0']) ?>

OUTPUT

Welcome Yii2.0

yii2.0 widget creation
I think it may be to helpful to you.