Using the Bootstrap widget

Yii2 supports Bootstrap as a core feature. Bootstrap framework CSS and JavaScript files are injected by default in all pages and we could even use this feature to only apply CSS classes or call our own JavaScript function provided by Bootstrap.

However, Yii2 embeds Bootstrap as a widget, and we can access this framework's capabilities like any other widget.

The most used are:

Class name

Description

yiiootstrapAlert

This class renders an alert Bootstrap component

yiiootstrapButton

This class renders a Bootstrap button

yiiootstrapDropdown

This class renders a Bootstrap drop-down menu component

yiiootstrapNav

This class renders a nav HTML component

yiiootstrapNavBar

This class renders a navbar HTML component

For example, yiiootstrapNav and yiiootstrapNavBar are used in the default main template.

This is an extract from the main layout view (in basic/views/layouts/main.php):

        <?php
            NavBar::begin([
                'brandLabel' => 'My Company',
                'brandUrl' => Yii::$app->homeUrl,
                'options' => [
                    'class' => 'navbar-inverse navbar-fixed-top',
                ],
            ]);
            echo Nav::widget([
                'options' => ['class' => 'navbar-nav navbar-right'],
                'items' => [
                    ['label' => 'Home', 'url' => ['/site/index']],
                    ['label' => 'About', 'url' => ['/site/about']],
                    ['label' => 'Contact', 'url' => ['/site/contact']],
                    Yii::$app->user->isGuest ?
                        ['label' => 'Login', 'url' => ['/site/login']] :
                        ['label' => 'Logout (' . Yii::$app->user->identity->username . ')',
                            'url' => ['/site/logout'],
                            'linkOptions' => ['data-method' => 'post']],
                ],
            ]);
            NavBar::end();
        ?>

Example: using datepicker

Yii2 also supports, by itself, many jQuery UI widgets through the JUI extension for Yii2, yii2-jui.

If we do not have the yii2-jui extension in the vendor folder, we can get it from Composer using this command:

php composer.phar require --prefer-dist yiisoft/yii2-jui

In this example, we will discuss the two most used widgets: datepicker and autocomplete. First let's have a look at the datepicker widget. This widget can be initialized using a model attribute or by filling out a value property. The following is an example made using a model instance and one of its attributes:

echo DatePicker::widget([
    'model' => $model,
    'attribute' => 'from_date',
    //'language' => 'it',
    //'dateFormat' => 'yyyy-MM-dd',
]);

And here is a sample of the value property's use:

echo DatePicker::widget([
    'name'  => 'from_date',
    'value'  => $value,
    //'language' => 'it',
    //'dateFormat' => 'yyyy-MM-dd',
]);

Now create a new controller named JuiWidgetsController in basic/controllers/JuiWidgetsController.php:

<?php

namespace appcontrollers;

use Yii;
use yiiwebController;
use appmodelsReservation;

class JuiWidgetsController extends Controller
{
    public function actionDatePicker()
    {
        $reservationUpdated = false;
        
        $reservation = Reservation::findOne(1);
        
        if(isset($_POST['Reservation']))
        {
            $reservation->load( Yii::$app->request->post() );
            
            $reservation->date_from = Yii::$app->formatter->asDate(  date_create_from_format('d/m/Y', $reservation->date_from), 'php:Y-m-d' );
            $reservation->date_to = Yii::$app->formatter->asDate(  date_create_from_format('d/m/Y', $reservation->date_to), 'php:Y-m-d' );
            
            $reservationUpdated = $reservation->save();
        }
        
        return $this->render('datePicker', ['reservation' => $reservation, 'reservationUpdated' => $reservationUpdated]);
    }
}

In this action, we define the $reservation model, picking from the reservations database table with id 1.

When data is sent via POST, the date_from and date_to fields will be converted from the d/m/y to the y-m-d format to make it possible for the database to save data. Then the model object is updated through the save() method. Using the Bootstrap widget, an alert box will be displayed in the view after updating the model.

Create the datePicker view in basic/views/jui-widgets/datePicker.php:

<?php

use yiihelpersHtml;
use yiiwidgetsActiveForm;
use yiijuiDatePicker;

?>

<div class="row">
    <div class="col-lg-6">
        <h3>Date Picker from Value<br />(using MM/dd/yyyy format and English language)</h3>
        <?php
            $value = date('Y-m-d');
            
        echo DatePicker::widget([
            'name'  => 'from_date',
            'value'  => $value,
            'language' => 'en',
            'dateFormat' => 'MM/dd/yyyy',
        ]);
        ?>
    </div>
    <div class="col-lg-6">
        
        <?php if($reservationUpdated) { ?>
            <?php
            echo yiiootstrapAlert::widget([
                'options' => [
                    'class' => 'alert-success',
                ],
                'body' => 'Reservation successfully updated',
            ]);   
            ?>         
        <?php } ?>
        
        <?php $form = ActiveForm::begin(); ?>
        
        <h3>Date Picker from Model<br />(using dd/MM/yyyy format and italian language)</h3>
        
        <br />
        
        <label>Date from</label>
        <?php
        // First implementation of DatePicker Widget
        echo DatePicker::widget([
            'model'  => $reservation,
            'attribute' => 'date_from',
            'language' => 'it',
            'dateFormat' => 'dd/MM/yyyy',
        ]);
        ?>
   
        <br />
        <br />
        
        <?php
        // Second implementation of DatePicker Widget
        echo $form->field($reservation, 'date_to')->widget(yiijuiDatePicker::classname(), [
                'language' => 'it',
                'dateFormat' => 'dd/MM/yyyy',
        ]) ?>        
        
        <?php     
            echo Html::submitButton('Send', ['class' => 'btn btn-primary'])
        ?>

        <?php $form = ActiveForm::end(); ?>
        
    </div>
</div>

The view is split into two columns, left and right. The left column simply displays a DataPicker example from the value (fixed to the current date). The right column displays an alert box if the $reservation model has been updated and the next two kinds of widget declaration too; the first one without using $form and the second one using $form, both outputting the same HTML code.

In either case, the DatePicker date output format is set to dd/MM/yyyy through the dateFormat property and the language is set to Italian through the language property.

Point your browser to http://hostname/basic/web/jui-widgets/date-picker to see the following output:

Example: using datepicker

Using datepicker

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.125.7