Google News
logo
Yii framework - Interview Questions
What is Widgets in Yii Framework?
Widgets are reusable building blocks used in views to create complex and configurable user interface elements in an object-oriented fashion. For example, a date picker widget may generate a fancy date picker that allows users to pick a date as their input. All you need to do is just to insert the code in a view like the following :
<?php
use yii\jui\DatePicker;
?>
<?= DatePicker::widget(['name' => 'date']) ?>
There are a good number of widgets bundled with Yii, such as active form, menu, jQuery UI widgets, Twitter Bootstrap widgets. In the following, we will introduce the basic knowledge about widgets. Please refer to the class API documentation if you want to learn about the usage of a particular widget.
 
Using Widgets : Widgets are primarily used in views. You can call the yii\base\Widget::widget() method to use a widget in a view. The method takes a configuration array for initializing the widget and returns the rendering result of the widget. For example, the following code inserts a date picker widget which is configured to use the Russian language and keep the input in the from_date attribute of $model.
<?php
use yii\jui\DatePicker;
?>
<?= DatePicker::widget([
    'model' => $model,
    'attribute' => 'from_date',
    'language' => 'ru',
    'dateFormat' => 'php:Y-m-d',
]) ?>
Some widgets can take a block of content which should be enclosed between the invocation of yii\base\Widget::begin() and yii\base\Widget::end(). For example, the following code uses the yii\widgets\ActiveForm widget to generate a login form. The widget will generate the opening and closing <form> tags at the place where begin() and end() are called, respectively. Anything in between will be rendered as is.
<?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 unlike yii\base\Widget::widget() which returns the rendering result of a widget, the method yii\base\Widget::begin() returns an instance of the widget which you can use to build the widget content.
 
 
Configuring global defaults : Global defaults for a widget type could be configured via DI container :
\Yii::$container->set('yii\widgets\LinkPager', ['maxButtonCount' => 5]);
Advertisement