1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
<?php
/**
* @link https://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license https://www.yiiframework.com/license/
*/
namespace yii\bootstrap4;
use yii\helpers\ArrayHelper;
/**
* ButtonGroup renders a button group bootstrap component.
*
* For example,
*
* ```php
* // a button group with items configuration
* echo ButtonGroup::widget([
* 'buttons' => [
* ['label' => 'A'],
* ['label' => 'B'],
* ['label' => 'C', 'visible' => false],
* ]
* ]);
*
* // button group with an item as a string
* echo ButtonGroup::widget([
* 'buttons' => [
* Button::widget(['label' => 'A']),
* ['label' => 'B'],
* ]
* ]);
* ```
*
* Pressing on the button should be handled via JavaScript. See the following for details:
*
* @see https://getbootstrap.com/docs/4.5/components/buttons/
* @see https://getbootstrap.com/docs/4.5/components/button-group/
*
* @author Antonio Ramirez <amigo.cobos@gmail.com>
* @author Simon Karlen <simi.albi@outlook.com>
*/
class ButtonGroup extends Widget
{
/**
* @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:
*
* - label: string, required, the button label.
* - options: array, optional, the HTML attributes of the button.
* - visible: bool, optional, whether this button is visible. Defaults to true.
*/
public $buttons = [];
/**
* @var bool whether to HTML-encode the button labels.
*/
public $encodeLabels = true;
/**
* {@inheritdoc}
*/
public function init()
{
parent::init();
Html::addCssClass($this->options, ['widget' => 'btn-group']);
if (!isset($this->options['role'])) {
$this->options['role'] = 'group';
}
}
/**
* {@inheritdoc}
* @throws \Exception
*/
public function run()
{
BootstrapAsset::register($this->getView());
return Html::tag('div', $this->renderButtons(), $this->options);
}
/**
* Generates the buttons that compound the group as specified on [[buttons]].
* @return string the rendering result.
* @throws \Exception
*/
protected function renderButtons()
{
$buttons = [];
foreach ($this->buttons as $button) {
if (is_array($button)) {
$visible = ArrayHelper::remove($button, 'visible', true);
if ($visible === false) {
continue;
}
$button['view'] = $this->getView();
if (!isset($button['encodeLabel'])) {
$button['encodeLabel'] = $this->encodeLabels;
}
if (!isset($button['options'], $button['options']['type'])) {
ArrayHelper::setValue($button, 'options.type', 'button');
}
$buttons[] = Button::widget($button);
} else {
$buttons[] = $button;
}
}
return implode("\n", $buttons);
}
}