ButtonGroup.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\bootstrap;
  8. use yii\helpers\ArrayHelper;
  9. use yii\helpers\Html;
  10. /**
  11. * ButtonGroup renders a button group bootstrap component.
  12. *
  13. * For example,
  14. *
  15. * ```php
  16. * // a button group with items configuration
  17. * echo ButtonGroup::widget([
  18. * 'buttons' => [
  19. * ['label' => 'A'],
  20. * ['label' => 'B'],
  21. * ]
  22. * ]);
  23. *
  24. * // button group with an item as a string
  25. * echo ButtonGroup::widget([
  26. * 'buttons' => [
  27. * Button::widget(['label' => 'A']),
  28. * ['label' => 'B'],
  29. * ]
  30. * ]);
  31. * ```
  32. * @see http://getbootstrap.com/javascript/#buttons
  33. * @see http://getbootstrap.com/components/#btn-groups
  34. * @author Antonio Ramirez <amigo.cobos@gmail.com>
  35. * @since 2.0
  36. */
  37. class ButtonGroup extends Widget
  38. {
  39. /**
  40. * @var array list of buttons. Each array element represents a single button
  41. * which can be specified as a string or an array of the following structure:
  42. *
  43. * - label: string, required, the button label.
  44. * - options: array, optional, the HTML attributes of the button.
  45. */
  46. public $buttons = [];
  47. /**
  48. * @var boolean whether to HTML-encode the button labels.
  49. */
  50. public $encodeLabels = true;
  51. /**
  52. * Initializes the widget.
  53. * If you override this method, make sure you call the parent implementation first.
  54. */
  55. public function init()
  56. {
  57. parent::init();
  58. Html::addCssClass($this->options, 'btn-group');
  59. }
  60. /**
  61. * Renders the widget.
  62. */
  63. public function run()
  64. {
  65. echo Html::tag('div', $this->renderButtons(), $this->options);
  66. BootstrapAsset::register($this->getView());
  67. }
  68. /**
  69. * Generates the buttons that compound the group as specified on [[buttons]].
  70. * @return string the rendering result.
  71. */
  72. protected function renderButtons()
  73. {
  74. $buttons = [];
  75. foreach ($this->buttons as $button) {
  76. if (is_array($button)) {
  77. $label = ArrayHelper::getValue($button, 'label');
  78. $options = ArrayHelper::getValue($button, 'options');
  79. $buttons[] = Button::widget([
  80. 'label' => $label,
  81. 'options' => $options,
  82. 'encodeLabel' => $this->encodeLabels,
  83. 'view' => $this->getView()
  84. ]);
  85. } else {
  86. $buttons[] = $button;
  87. }
  88. }
  89. return implode("\n", $buttons);
  90. }
  91. }