Widget.php 2.23 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
{
	/**
	 * @var array the HTML attributes for the widget container tag.
	 */
Alexander Makarov committed
25
	public $options = [];
26
	/**
27 28 29 30
	 * @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").
31
	 */
Alexander Makarov committed
32
	public $clientOptions = [];
33
	/**
34 35 36 37
	 * @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").
38
	 */
Alexander Makarov committed
39
	public $clientEvents = [];
Antonio Ramirez committed
40

41 42

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

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

		BootstrapPluginAsset::register($view);

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

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

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