Create a Simple to Complex Widget in Yii

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.

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

View: site/hellowidget.php


Leave a Reply

Your email address will not be published. Required fields are marked *