Widget.php 2.48 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 11

use Yii;
use yii\base\View;
12
use yii\helpers\Json;
13

14
/**
15
 * \yii\bootstrap\Widget is the base class for all bootstrap widgets.
16 17
 *
 * @author Antonio Ramirez <amigo.cobos@gmail.com>
18
 * @author Qiang Xue <qiang.xue@gmail.com>
19 20
 * @since 2.0
 */
21
class Widget extends \yii\base\Widget
22 23
{
	/**
24
	 * @var boolean whether to use the responsive version of Bootstrap.
25
	 */
Antonio Ramirez committed
26
	public static $responsive = true;
27 28 29
	/**
	 * @var array the HTML attributes for the widget container tag.
	 */
30
	public $options = array();
31
	/**
32 33 34 35
	 * @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://twitter.github.io/bootstrap/javascript.html#modals) shows
	 * how to use the "Modal" plugin and the supported options (e.g. "remote").
36
	 */
37
	public $clientOptions = array();
38
	/**
39 40 41 42
	 * @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://twitter.github.io/bootstrap/javascript.html#modals) shows
	 * how to use the "Modal" plugin and the supported events (e.g. "shown").
43
	 */
44
	public $clientEvents = array();
Antonio Ramirez committed
45

46 47

	/**
48 49 50
	 * Initializes the widget.
	 * This method will register the bootstrap asset bundle. If you override this method,
	 * make sure you call the parent implementation first.
51
	 */
52
	public function init()
53
	{
54
		parent::init();
Alexander Kochetov committed
55 56
		if (!isset($this->options['id'])) {
			$this->options['id'] = $this->getId();
57
		}
58 59 60
	}

	/**
61 62
	 * Registers a specific Bootstrap plugin and the related events
	 * @param string $name the name of the Bootstrap plugin
63
	 */
64
	protected function registerPlugin($name)
65
	{
Alexander Kochetov committed
66
		$id = $this->options['id'];
67
		$view = $this->getView();
68
		$view->registerAssetBundle(static::$responsive ? 'yii/bootstrap/responsive' : 'yii/bootstrap');
69
		$view->registerAssetBundle("yii/bootstrap/$name");
70

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

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