O
O
Oklick2016-12-20 22:18:19
Yii
Oklick, 2016-12-20 22:18:19

How to add custom tag to Yii2 form element?

Good day.
The website has this piece of code:

<?php
    $form = ActiveForm::begin();
    foreach ($categoryParams as $v) {
        $inputParams = $paramsArray[$v];
        ?>
        <div class="filterParam_<?= $v ?> filterParam">
            <?php
            $inp = $form->field($modelGoods, $v);
            switch ($inputParams['user_type']) {
                case 'checkbox':
                    $inp->checkboxList($inputParams['label_values'], ['encode' => false]);
                    break;
                case 'radio':
                    $inp->radioList($inputParams['label_values'], ['encode' => false]);
                    break;
                case 'input':
                default:
                    $inp->textInput(['maxlength' => true]);
            }
            echo $inp->label($inputParams['label_user']);
            ?>
        </div>
        <?php
    }
    ?>

It produces this html:
<div class="filterParam_sex filterParam">
<div class="form-group field-goods-sex">
<label class="control-label">
<span>Пол</span> <span></span> <span>Очистить</span>
</label>
<input type="hidden" name="Goods[sex]" value="">
<div id="goods-sex">
<label><input type="checkbox" name="Goods[sex][]" value="1"> Все</label>
<label><input type="checkbox" name="Goods[sex][]" value="2"> Мужской</label>
<label><input type="checkbox" name="Goods[sex][]" value="3"> Женский</label>
<div class="help-block">
</div>
</div>        
</div>

Everything seems to be fine, but the problem is that I need the input to be associated with the label by ID and lie not inside it, but next to it.
Tell me how to do it? Googled but couldn't find an answer. I looked at the possibility of template, but I could not do what I need with it.
Thanks in advance.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Fedorov, 2016-12-21
@Oklick

If I understand correctly, you need to customize the checkbox display template inside the checkboxList. Unfortunately, yii does not provide the ability to configure one template for all checkboxes in the checkboxList, but the appearance of each checkbox can be generated independently. Actually, to solve your problem, you can use this, for example:

$inp->checkboxList($inputParams['label_values'], [
    'encode' => false,
    'item' => function ($index, $label, $name, $checked, $value){            
        $id = "ch{$index}";
        return Html::beginTag('div',['class' =>'checkbox']) . Html::label($label,$id) . Html::checkbox($name,$checked,['id'=>$id]) . Html::endTag('div');             
    } 
]);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question