Skip to content

How to create custom widget in Yii2

Last updated on December 21, 2022

This tutorial will show you how you can create your own custom widget in Yii2. Widgets are reusable blocks and they are used in your views. The main advantage of a Widget is you can write once and reuse it wherever you need it in your view.

To create a custom widget we must extend the base widget yii\base\Widget and we have to override the init() and/or run() methods of the base widget.

Here are the simple steps for creating a custom widget.

Step1:
Make a folder named “components” in your project root folder.

step2:
Create a file with desired widget name inside the components folder and copy paste the below code and change the class name in the code. Example – Mywidget.php

namespace app\components;
use yii\base\Widget;
use yii\helpers\Html;
class Mywidget extends Widget {
	public $message;
	public function init() {
		// your logic here
		parent::init();
		if ($this->message === null) {
			$this->message = 'Welcome Guest';
		} else {
			$this->message = 'Welcome ' . $this->message;
		}
	}
	public function run(){
	    // you can load & return the view or you can return the output variable
	    return $this->render('myWidget', ['message' => $this->message]);
	}
}

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

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

Step3:
You are done! Now you can use your widget inside any of your app views.

Usage example –

echo \app\components\MyWidget::widget();

0 0 votes
Article Rating
Subscribe
Notify of
guest

3 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments