O Connor O Connor - 3 months ago 35
PHP Question

How to remove class from the DIV parents from checkboxList() in Yii framework 2

Below is my code to generate a checkbox list in Yii framework 2.

<?php $form = ActiveForm::begin(); ?>
<?php echo $form->field($model, 'my_property')->checkboxList(['A', 'B', 'C']) ?>
<?php ActiveForm::end(); ?>


This generates the follow HTML checkbox list.

<div class="form-group">
<label class="control-label" for="my_property">My Property</label>
<input type="hidden" name="Model[my_property]" value="">
<div id="model-my_property">
<div class="checkbox">
<label>
<input type="checkbox" name="Model[my_property][]" value="0"> A
</label>
</div>
<div class="checkbox">
<label>
<input type="checkbox" name="Model[my_property][]" value="1"> B
</label>
</div>
<div class="checkbox">
<label>
<input type="checkbox" name="Model[my_property][]" value="2"> C
</label>
</div>
</div>
<p class="help-block help-block-error"></p>
</div>


How can I remove the
class="checkbox"
from the
div
which directly is surrounding the
<label>
tag? I have tried
template
,
checkboxTemplate
and
inputTemplate
, with these I can only touch the outer
div
.

Answer

I guess you are using yii\bootstrap\ActiveForm and not default yii\widgets\ActiveForm because there is this element styled.

Easiest solution - use the second ActiveForm class so it will be unstyled.

And if you don't want to change ActiveForm class:

$form
->field($model, 'my_property')
->checkboxList(
    ['A', 'B', 'C'],
    ['item' => function ($index, $label, $name, $checked, $value) {
        return '<div>'
                . '<label>'
                . '<input type="checkbox" name="' . $name . '" value="' . $value . '"> '
                . $label 
                . '</label>'
                . '</div>';
    }]
);