A button group will not work with automatically generated checkboxes because yii2 adds a div and a help box for errors. So what you can do is create a hidden form and associate a group of buttons with it through jQuery. I created the code you need and made it work in my yii installation. All you have to do is replace <model name> with your model name.
<?php use yii\bootstrap\ButtonGroup; use yii\bootstrap\ActiveForm; use yii\web\View; ?> <?= ButtonGroup::widget([ 'buttons' => [ ['label' => 'Checkbox 1', 'options'=>['class'=>'btn btn-primary', 'id'=>'button1', 'autocomplete'=>'off', 'aria-pressed'=>'false']], ['label' => 'Checkbox 2', 'options'=>['class'=>'btn btn-primary', 'id'=>'button2', 'autocomplete'=>'off', 'aria-pressed'=>'false']], ['label' => 'Checkbox 3', 'options'=>['class'=>'btn btn-primary', 'id'=>'button3', 'autocomplete'=>'off', 'aria-pressed'=>'false']], ] ]); ?> <?php $form = ActiveForm::begin(); ?> <?= $form->field($model, 'field1')->hiddenInput()->label(false) ?> <?= $form->field($model, 'field2')->hiddenInput()->label(false) ?> <?= $form->field($model, 'field3')->hiddenInput()->label(false) ?> <?php ActiveForm::end();?> <?php $script = <<< JS if($('#<model name>-field1').val()=='1'){ $('#button1').addClass('active'); $('#button1').attr('aria-pressed', 'true'); } if($('#<model name>-field2').val()=='1'){ $('#button2').addClass('active'); $('#button2').attr('aria-pressed', 'true'); } if($('#<model name>-field3').val()=='1'){ $('#button3').addClass('active'); $('#button3').attr('aria-pressed', 'true'); } $('.btn').on('click', function () { $(this).button('toggle') $(this).blur(); }); $('#button1').on('click', function () { if($('#button1').attr('aria-pressed')== 'true'){ $('#<model name>-field1').val('1') } else { $('#<model name>-field1').val('0') } }); $('#button2').on('click', function () { if($('#button2').attr('aria-pressed')== 'true'){ $('#<model name>-field2').val('1') } else { $('#<model name>-field2').val('0') } }); $('#button3').on('click', function () { if($('#button3').attr('aria-pressed')== 'true'){ $('#<model name>-field3').val('1') } else { $('#<model name>-field3').val('0') } }); JS; $this->registerJs($script, View::POS_END); ?>
source share