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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<?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
1 2 3 4 5 6 7 8 9 10 11 |
<?php .......... class SiteController extends Controller { ........... public function actionCreatewidget(){ return $this->render('hellowidget'); } ........... } ?> |
View: site/hellowidget.php
1 2 3 4 |
<?php use app\components\HelloWidget; ?> <?= HelloWidget::widget(['message' => ' Yii2.0']) ?> |
SRC:
http://www.bsourcecode.com/yiiframework2/how-to-create-custom-widget-in-yii2-0-framework/