The Krajee Switch Input widget for Yii2 based on Bootstrap Switch is great. I’ll write more about it in the near future.

However, I had one major problem with a gap in the documentation – others seem to have been confused as well. When you’re using the widget in SwitchInput::RADIO mode, it’s not well documented how to set the active radio button on load.

I load the widget three times in a table, each individually. Here’s an example:

[php]
echo SwitchInput::widget([
‘type’ => SwitchInput::RADIO,
‘name’ => ‘place-chooser’,
‘items’ => [
[ ‘value’ => $model->id],
],
‘value’ => $value,
‘pluginOptions’ => [ ‘size’ => ‘mini’,’handleWidth’=>60,’onText’ => ‘<i class="glyphicon glyphicon-ok"></i>’,’offText’=>'<i class="glyphicon glyphicon-remove"></i>’],
‘labelOptions’ => [‘style’ => ‘font-size: 12px’],
]);
[/php]

The radio switch will be ON at load if the items [ ‘value ‘ ] == the widget’s $value. In other words, the example below would be set to ON at load:

[php]
[ ‘value’ => 15],
],
‘value’ => 15,
[/php]

The piece that’s missing from the documentation is the need for the Widget ‘value’ key.

Support this site, share this page:Share on twitter

Twitter

Share on reddit

Reddit

Share on linkedin

Linkedin

Share on facebook

Facebook

Share on email

Email

Comments

  1. Kartik V

    As mentioned on the widget page, the docs does link to the reference that the widget extends from Yii Input widget – so one should treat this like any Yii Input widget. Your case above will not work for model and is only applicable if you are using without model.

    Note that you can set a value in Yii Input Widget in two ways (not the only way you have shown above)
    – Option 1: You do not need to set a value if you are using the widget with model and attribute (the value will be passed automatically)
    – Option 2: if you do not use model , you need to set the value property to set the initial value.

    This is true for all input widgets and has not been explicitly mentioned. But its good that you bring it up – so people know the properties of an input widget.