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

namespace yii\bootstrap;

Qiang Xue committed
10
use yii\helpers\ArrayHelper;
11 12 13 14 15 16 17 18 19 20
use yii\helpers\Html;

/**
 * ButtonGroup renders a button group bootstrap component.
 *
 * For example,
 *
 * ```php
 * // a button group with items configuration
 * echo ButtonGroup::::widget(array(
21
 *     'buttons' => array(
Qiang Xue committed
22 23
 *         array('label' => 'A'),
 *         array('label' => 'B'),
24 25 26 27 28
 *     )
 * ));
 *
 * // button group with an item as a string
 * echo ButtonGroup::::widget(array(
29
 *     'buttons' => array(
Qiang Xue committed
30 31
 *         Button::widget(array('label' => 'A')),
 *         array('label' => 'B'),
32 33 34 35 36 37 38 39 40 41 42
 *     )
 * ));
 * ```
 * @see http://twitter.github.io/bootstrap/javascript.html#buttons
 * @see http://twitter.github.io/bootstrap/components.html#buttonGroups
 * @author Antonio Ramirez <amigo.cobos@gmail.com>
 * @since 2.0
 */
class ButtonGroup extends Widget
{
	/**
Qiang Xue committed
43 44
	 * @var array list of buttons. Each array element represents a single button
	 * which can be specified as a string or an array of the following structure:
45 46 47 48
	 *
	 * - label: string, required, the button label.
	 * - options: array, optional, the HTML attributes of the button.
	 */
Qiang Xue committed
49
	public $buttons = array();
50
	/**
Qiang Xue committed
51
	 * @var boolean whether to HTML-encode the button labels.
52 53 54 55 56 57 58 59 60 61 62
	 */
	public $encodeLabels = true;


	/**
	 * Initializes the widget.
	 * If you override this method, make sure you call the parent implementation first.
	 */
	public function init()
	{
		parent::init();
63
		Html::addCssClass($this->options, 'btn-group');
64 65 66 67 68 69 70
	}

	/**
	 * Renders the widget.
	 */
	public function run()
	{
Qiang Xue committed
71
		echo Html::tag('div', $this->renderButtons(), $this->options);
72
		BootstrapAsset::register($this->getView());
73 74 75 76 77 78
	}

	/**
	 * Generates the buttons that compound the group as specified on [[items]].
	 * @return string the rendering result.
	 */
Qiang Xue committed
79
	protected function renderButtons()
80 81
	{
		$buttons = array();
Qiang Xue committed
82 83 84 85 86
		foreach ($this->buttons as $button) {
			if (is_array($button)) {
				$label = ArrayHelper::getValue($button, 'label');
				$options = ArrayHelper::getValue($button, 'options');
				$buttons[] = Button::widget(array(
87 88 89
					'label' => $label,
					'options' => $options,
					'encodeLabel' => $this->encodeLabels
Qiang Xue committed
90 91 92 93
				));
			} else {
				$buttons[] = $button;
			}
94 95 96
		}
		return implode("\n", $buttons);
	}
Qiang Xue committed
97
}