Home > Article > PHP Framework > How to use widgets of yii framework
Widgets
Widgets are reusable units used in views, using object-oriented way to create complex and configurable user interface elements. (Recommended learning: yii framework)
For example, the date picker widget can generate an exquisite date picker that allows users to select dates. You only need to insert the following code in the view:
<?php use yii\jui\DatePicker; ?> <?= DatePicker::widget(['name' => 'date']) ?>
Yii provides many excellent widgets, such as active form, menu, jQuery UI widgets, and Twitter Bootstrap widgets. Next, we will introduce the basic knowledge of widgets. If you want to know about a certain widget, please refer to the corresponding class API document.
Using widgets
Widgets are basically used in views. The yii\base\Widget::widget() method can be called in the view to use widgets. This method initializes the widget using the configuration array and returns the result of the widget being rendered.
For example, the following code inserts a date picker widget, which is configured to use Russian, and the input box content is the from_date attribute value of $model.
<?php use yii\jui\DatePicker; ?> <?= DatePicker::widget([ 'model' => $model, 'attribute' => 'from_date', 'language' => 'ru', 'dateFormat' => 'php:Y-m-d', ]) ?>
Some widgets can use data content in yii\base\Widget::begin() and yii\base\Widget::end() calls.
For example, the following code uses the yii\widgets\ActiveForm widget to generate a login form. The widget will generate the start tag and end tag of ff9c23ada1bcecdd1a0fb5d5a0f18437 at the execution locations of begin() and end() respectively. The middle Any code will also be rendered.
<?php use yii\widgets\ActiveForm; use yii\helpers\Html; ?> <?php $form = ActiveForm::begin(['id' => 'login-form']); ?> <?= $form->field($model, 'username') ?> <?= $form->field($model, 'password')->passwordInput() ?> <div class="form-group"> <?= Html::submitButton('Login') ?> </div> <?php ActiveForm::end(); ?>
Note that the rendering result returned by calling yii\base\Widget::widget() is different. Calling the yii\base\Widget::begin() method returns a widget instance that can assemble the widget content.
Note: When calling yii\base\Widget::end(), some widgets will use output buffering to adjust the enclosed content. Therefore, when calling yii\base\Widget::begin() and yii\base\Widget::end(), it is best to be in the same view file. Failure to follow this rule may result in unexpected output.
The above is the detailed content of How to use widgets of yii framework. For more information, please follow other related articles on the PHP Chinese website!