Creating widgets
A widget is a reusable client-side code (containing JavaScript, CSS, and HTML) with minimal logic wrapped in a yii\base\Widget
object that we can easily insert and apply in any view.
Building a widget requires you to extend two methods of yii\base\Widget
:
- 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.
The first method, begin()
, accepts a function parameter...