Widgets are reusable building blocks on client-side (containing JavaScript, HTML and CSS). They are used to create complex and configurable user interface elements in views.

For example, a Progress widget and DatePicker widget can create a progress bar and stylist date picker in your application.


Using Widgets

Widgets are majorly used in views. To call a widget you can call,

  1. yii\base\Widget::widget()  

This method takes a configuration array for initializing the widget.

For example, the following code inserts a date picker widget configured to use Russian language.

  1. <?php  
  2. use yii\jui\DatePicker;  
  3. ?>  
  4. <?= DatePicker::widget([  
  5.     'model' => $model,  
  6.     'attribute' => 'from_date',  
  7.     'language' => 'ru',  
  8.     'clientOptions' => [  
  9.         'dateFormat' => 'yy-mm-dd',  
  10.     ],  
  11. ])   
  12. ?>  

Example

In this example, we'll use progress widget.

Step 1 Create an action actionWidget() in the SiteController.php file in the frontend directory.

  1. public function actionWidget()   
  2.     {   
  3.    return $this->render('widget');   
  4.     }  

Look at the above code, we are rendering to the widget page in view folder.

Step 2 Create a page widget.php in the views/site folder in the frontend directory.

  1. <?php   
  2.    use yii\bootstrap\Progress;   
  3. ?>   
  4. <?= Progress::widget(['percent' => 99, 'label' => 'Loading 99%']) ?>  

Step 3 Run it on the browser with the URL,

http://localhost/wid/frontend/web/index.php?r=site/widget

YII Widgets 1