How to create your own widget in Yii2
Home » BLOG » Yii2.0 framework » How to create your own widget in Yii2

How to create your own widget in Yii2

category:  Yii2.0 framework

Widgets are reusable building blocks. They are used in views in the MVC framework. If you are working on page builders (eg. Elementor) in WordPress, you have experience in using the widgets. In this post, I will share how to create your own widget in Yii2.

Yii2 widget

In Yii2, you will see how the widget is used by using the date picker widget below. In the view files, add the namespace of the DatePicker widget and call the DatePicker widget.

<?php
// namespace
use yii\jui\DatePicker;

// call date picker widget
<?= DatePicker::widget(['name' => 'date']) ?>

The result of the DatePicker widget is below.

Date Picker Widget in Yii2

Create your own widget in Yii2

  • Create the new widget file(PHP file) under the widgets folder

The widgets folder should already be created after installing Yii2. If not, you can create the widgets folder in the application root folder. I use the Yii2 advanced template and I want to add the new widget to the frontend. So I will create a new widget file under the frontend/widgets folder. I name my widget file as “NoteWidget.php“.

Here is my application structure.
– web
– widgets
— NoteWidget.php

The NoteWidget purpose is to just show the note in my application.

  • Add the widget code

In the NoteWidget file, we will add the code below.

<?php
namespace app\widgets;

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

class NoteWidget extends Widget{
	public $message;
	
	public function init(){
		parent::init();
	}
	
	public function run(){
		return 
		'<div class="callout callout-notification">
			<i class="fa fa-check"></i> '. Html::encode($this->message) .'
		</div>';
	}
}
?>

Important note: the widget file and widget class must be the same name. In our post, the widget file names “NoteWidget” and our widget class names “NoteWidget”. They both are the same name. Otherwise, you will see the widget not found error.

  • Code Explanation

Basically, in Yii2, we will extend our new widget class from the yii\base\Widget class. Then we will override the init() and run() methods of the Widget class. The init() method will initialize the widget properties. The run() method will generate the rendering result from the widget.

Breaking down, first, we declare the “app\widgetsnamespace. Then we tell Yii2 that we will use the yii\base\Widget class and its alias is Widget by default. The class alias will be referred to as this class in our code.

We also tell Yii2 that we will use the yii\helpers\HTML class. This class is optional. In the code, we just use it to encode the input message before rendering it out on the page (eg. Html::encode() ).

In the code above, our NoteWidget extends the Yii2 Widget class. In the NoteWidget class, we create the message public variable. So in the view file, we can pass the message we want to the NoteWidget via this message variable. In the init() method, we call the parent’s constructor ( eg. parent::init() ). In the run() method, we return the HTML with our message. And that’s it for our NoteWidget.

How to use your widget in the view files

In our view files, we will tell Yii2 that we use our NoteWidget class. Then we call our NoteWidget class as code below.

<?php
/* @var $this yii\web\View */

// Tell Yii2 that we use NoteWidget class
use app\widgets\NoteWidget;
?>

// Call NoteWidget and passing the message
<?= NoteWidget::widget(['message' => 'This is our message.']) ?>

And that’s it. It is simple and easy to use.

More info

Using view for rendering the widget

If your result from the widget is big, you should consider outputting the result in a view instead of embedding the content within the run() method. Learn more on how to render in Widget.

Begin() and end() methods

In some situations, you may want to use the PHP’s output buffer. In my case, is to generate the PDF file using HTML. Using begin() and end() methods will be helpful. Below is an example.

namespace app\widgets;

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

class SampleWidget extends Widget
{
    public function init()
    {
        parent::init();
        ob_start();
    }

    public function run()
    {
        $content = ob_get_clean();
        return Html::encode($content);
    }
}

In the view file, you can use this SampleWidget as below.

<?php
use app\widgets\SampleWidget;
?>
<?php SampleWidget::begin(); ?>

    Your content is here...


    // Optional: You can also use the view file here to render the big content
    // The widget view files should be stored in "widgets/views" folder.
    <?php echo $this->render('viewfile'); ?> 

<?php SampleWidget::end(); ?>

Useful links

Wrap up

Using the widget, you can create the chart widget, note widget, notification widget, and more. You can add the widgets to any view files. Keep in mind that the widget is for reusing the view code. Creating the widgets should follow the MVC pattern as same as creating the Yii2 module. The widgets should be used without any required external resources. Just like you work on WordPress and use the page builder. On the page editor, you can drop any element widget (title, text, image, etc) on the page. Those element widgets don’t depend on any other resource. And this is how the widget should be reusable. Hopefully, my post saves your time. Please consider buying me coffee for writing more posts.