Widget.php 2.53 KB
Newer Older
1 2 3 4 5 6 7
<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

Antonio Ramirez committed
8
namespace yii\bootstrap;
9 10

use Yii;
11
use yii\helpers\Json;
12

13
/**
14
 * \yii\bootstrap\Widget is the base class for all bootstrap widgets.
15 16
 *
 * @author Antonio Ramirez <amigo.cobos@gmail.com>
17
 * @author Qiang Xue <qiang.xue@gmail.com>
18 19
 * @since 2.0
 */
20
class Widget extends \yii\base\Widget
21
{
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
    /**
     * @var array the HTML attributes for the widget container tag.
     * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
     */
    public $options = [];
    /**
     * @var array the options for the underlying Bootstrap JS plugin.
     * Please refer to the corresponding Bootstrap plugin Web page for possible options.
     * For example, [this page](http://getbootstrap.com/javascript/#modals) shows
     * how to use the "Modal" plugin and the supported options (e.g. "remote").
     */
    public $clientOptions = [];
    /**
     * @var array the event handlers for the underlying Bootstrap JS plugin.
     * Please refer to the corresponding Bootstrap plugin Web page for possible events.
     * For example, [this page](http://getbootstrap.com/javascript/#modals) shows
     * how to use the "Modal" plugin and the supported events (e.g. "shown").
     */
    public $clientEvents = [];
Antonio Ramirez committed
41

42 43 44 45 46 47 48 49 50 51 52 53
    /**
     * Initializes the widget.
     * This method will register the bootstrap asset bundle. If you override this method,
     * make sure you call the parent implementation first.
     */
    public function init()
    {
        parent::init();
        if (!isset($this->options['id'])) {
            $this->options['id'] = $this->getId();
        }
    }
54

55 56 57 58 59 60 61
    /**
     * Registers a specific Bootstrap plugin and the related events
     * @param string $name the name of the Bootstrap plugin
     */
    protected function registerPlugin($name)
    {
        $view = $this->getView();
62

63
        BootstrapPluginAsset::register($view);
64

65
        $id = $this->options['id'];
66

67 68 69 70 71
        if ($this->clientOptions !== false) {
            $options = empty($this->clientOptions) ? '' : Json::encode($this->clientOptions);
            $js = "jQuery('#$id').$name($options);";
            $view->registerJs($js);
        }
72

73 74 75 76 77 78 79 80
        if (!empty($this->clientEvents)) {
            $js = [];
            foreach ($this->clientEvents as $event => $handler) {
                $js[] = "jQuery('#$id').on('$event', $handler);";
            }
            $view->registerJs(implode("\n", $js));
        }
    }
81
}