Hi all,
I want to spice up one of my forms by replacing a short drop-down input field with a Bootstrap button group with nice descriptive icons.
However, the best solution I can find feels very hacky, and doesn’t use the Yii2-Bootstrap extension at all!
These are my problems:
-
The ButtonGroup widget from Yii2-Bootstrap doesn’t seem compatible with an ActiveForm radio list
-
The Html::radioList() method doesn’t seem to offer a “prompt” option like the dropDownList() method. This is a pity: the method providing the options array (getCategoryList) is also consumed by dropdown lists, so I cannot include the prompt in it. Therefore, I have to merge a default option in the array upon rendering, as you can see below
-
The radioList() method renders a hidden input, to provide a default value. This is all nice and dandy, but not necessary since I provide a checked default value myself and would like the GET parameters to be as short and descriptive as possible. Can I turn this off?
So if anyone has suggestions how to improve this code and make it more "Yii2 native", please advice!
Note that $filter is the name of my model.
<?=
$form->field($filter, 'filetype', ['options' => ['class' => 'col-xs-12']])->radioList(
ArrayHelper::merge(['' => \Yii::t('app','All file types')], $filter->getCategoryList()), // my crappy way to add an empty "prompt" default value
[
'class' => 'btn-group',
'data-toggle' => 'buttons',
'item' => function ($index, $label, $name, $checked, $value) use ($filter) {
return Html::label(
Html::radio(
$name,
$checked,
['id' => $name . '_' . $value, 'value' => $value]
) . $label,
$name . '_' . $value,
[
'class' => 'btn btn-primary' . ($value == $filter->filetype?' active':'') // my crappy way to make sure that the first button is checked when the value is null. Using $checked doesn't work
]
);
},
]
)
?>
Which looks like this: