yii2-bootstrap5/src/ButtonGroup.php

119 lines
3.2 KiB
PHP
Raw Normal View History

2021-02-10 05:04:59 +08:00
<?php
2021-08-07 05:38:53 +08:00
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
2021-02-10 05:04:59 +08:00
declare(strict_types=1);
namespace yii\bootstrap5;
use Throwable;
2021-02-10 05:04:59 +08:00
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:
*
2021-08-05 15:21:05 +08:00
* @see https://getbootstrap.com/docs/5.1/components/buttons/
* @see https://getbootstrap.com/docs/5.1/components/button-group/
2021-02-10 05:04:59 +08:00
*
* @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 = [];
2021-02-10 05:04:59 +08:00
/**
* @var bool whether to HTML-encode the button labels.
*/
public $encodeLabels = true;
2021-02-10 05:04:59 +08:00
/**
* {@inheritdoc}
*/
public function init()
{
parent::init();
Html::addCssClass($this->options, ['widget' => 'btn-group']);
if (!isset($this->options['role'])) {
$this->options['role'] = 'group';
}
}
/**
* {@inheritdoc}
* @return string
* @throws Throwable
2021-02-10 05:04:59 +08:00
*/
public function run(): string
{
BootstrapAsset::register($this->getView());
2021-02-10 05:04:59 +08:00
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 Throwable
2021-02-10 05:04:59 +08:00
*/
protected function renderButtons(): string
{
$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);
}
}