ButtonGroupInput.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: slava
  5. * Date: 18.04.17
  6. * Time: 11:07
  7. */
  8. namespace app\widgets;
  9. use yii\helpers\Html;
  10. use yii\widgets\InputWidget;
  11. class ButtonGroupInput extends InputWidget
  12. {
  13. /**
  14. * @inheritdoc
  15. */
  16. public $items = [];
  17. /**
  18. * @inheritdoc
  19. */
  20. public $type = 'default';
  21. /**
  22. * @inheritdoc
  23. */
  24. public $size = 'default';
  25. /**
  26. * @var bool
  27. */
  28. public $radio = true;
  29. /**
  30. * @inheritdoc
  31. */
  32. public function run()
  33. {
  34. $options = [
  35. 'class' => 'btn-group',
  36. 'data-toggle' => 'buttons',
  37. 'item' => [$this, 'renderItem'],
  38. 'style' => 'width: 100%;'
  39. ];
  40. if ($this->name) {
  41. $type = $this->radio ? 'radioList' : 'checkboxList';
  42. $result = Html::$type(
  43. $this->name,
  44. $this->value,
  45. $this->items,
  46. $options
  47. );
  48. } else {
  49. $type = $this->radio ? 'activeRadioList' : 'activeCheckboxList';
  50. $result = Html::$type(
  51. $this->model,
  52. $this->attribute,
  53. $this->items,
  54. $options
  55. );
  56. }
  57. return $result;
  58. }
  59. /**
  60. * @param int $index
  61. * @param string $label
  62. * @param string $name
  63. * @param bool $checked
  64. * @param int|string $value
  65. * @return string
  66. */
  67. public function renderItem($index, $label, $name, $checked, $value)
  68. {
  69. $input = $this->radio ? 'radio' : 'checkbox';
  70. return Html::$input(
  71. $name,
  72. $checked,
  73. [
  74. 'value' => $value,
  75. 'label' => $label,
  76. 'container' => false,
  77. 'labelOptions' => [
  78. 'class' => 'btn btn-' . $this->type . ' btn-' . $this->size . ($checked ? ' active' : ''),
  79. 'style' => 'width:' . (100 / count($this->items)) . '%',
  80. ],
  81. ]
  82. );
  83. }
  84. }