Learn to Create widgets in yii2 framework

 

A widget is a reusable client-side code (containing JavaScript, CSS, and HTML) with minimal logic wrapped in a yiibaseWidget object that we can easily insert and apply in any view.

Building a widget requires you to extend two methods of yiibaseWidget:

  • The init() method initializes the object
  • The run() method executes the object

In order to instance a widget, it is enough to call the static widget() method that accepts just one parameter or better still an array containing values for its public properties.

The following is an example:

    MyWidget::widget(['prop1' => 'value of prop1', …])

This returns a string containing widget output, passing its value value of prop1 for its prop1 public properties.

If we need to insert an extra code in a widget’s execution (for example, in the ActiveForm widget), we have a more complex way of instantiating the widget, using the begin() and end() methods.

Recommended :  Creating a Search Interface with React js

The first method, begin(), accepts a function parameter with a configuration array to pass to the widget, and it will return the widget object.

When the second method, end(), is called, the code between these two methods will be displayed and simultaneously, the end() method directly echoes the output of the widget run() method:

    $widget = MyWidget::begin(['prop1' => 'value of prop1', …]);

    ..
    .. I can use $widget object here  ..
    ..

     MyWidget::end();

As for any other views, in the run() method, we can refer to a view file, through the render() method, in order to display the widget output.

For example, a widget could be a real-time date/time clock. For this purpose, we will build a clock based on a block containing the date/time string updated by the JavaScript code. We can pass to widget construct time some values concerning for example, the color of the border box.

Recommended :  Learn to create Extensions in yii2 framework

To make an instance, let’s start with the basic template app (but this is obviously also valid for the advanced template app). Create a new folder (if it does not exist) named components in the root of the project at the same level of controllers, models, views, and so on, which will contain all the widgets we want to build.

Then, in this folder, we will create a new file named ClockWidget.php with the complete path basic/components/ClockWidget.php:

<?php

namespace appcomponents;

use yiibaseWidget;

class ClockWidget extends Widget
{

    public function init()
    {
        yiiwebJqueryAsset::register($this->getView());
    }
    
    public function run()
    {
        return $this->render('clock');
    }
    
}

In the init() method, we have also made references to the jQuery asset to request the framework to load the jQuery plugin, since we need it in the view file.

In the run() method, we have rendered the clock view, whose content will be discussed in next rows.

Recommended :  Learn how to import data from csv using Eloquent in Laravel

So, create a new folder at basic/components/views and, within it, a new file named clock.php with the following code:

<?php

$this->registerJs( <<< EOT_JS

    function ClockWidget_refresh_datetime()
    {
        var dateTimeString = new Date().toString();
        $('#ClockWidget_realtime_clock').html(dateTimeString);
    }

    setInterval(ClockWidget_refresh_datetime,1000);
    
    ClockWidget_refresh_datetime();
EOT_JS
);

?>

<div style="border:1px solid black;padding:5px;width:200px;text-align:center">
    <span id="ClockWidget_realtime_clock"></span>
</div>

This code simply displays a box with a string containing real-time values of the current date and time, updated every second.

Finally, we can use our widget in any view using this code:

<?= appcomponentsClockWidget::widget(); ?>

Example – creating a widget with a carousel

 

In this example, we will create a widget that consists of a carousel with some rooms (we can choose which one to display by passing them to the widget with the public property). Again, we will use a basic template application; however, everything is equally applicable to the advanced template apps.

About the author

Deven Rathore

I'm Deven Rathore, a multidisciplinary & self-taught designer with 3 years of experience. I'm passionate about technology, music, coffee, traveling and everything visually stimulating. Constantly learning and experiencing new things.

Pin It on Pinterest

Shares