S
S
secondmh2020-12-28 16:35:59
Yii
secondmh, 2020-12-28 16:35:59

Yii2 checkboxList how to put checked?

The page has a form with category filters. When the "Search" button is displayed, the data is displayed and you need to keep checked for those categories that have been selected. Can't figure out how to redefine checked, because comboboxlist value has values ​​1,2,...8, and the array, respectively, from index 0. As a result, the checkboxes jump one item lower. The list of categories is loaded from the database (because id starts from 1, for the selection I passed value from 1 to POST, ...). If you pass with value=0, 1 ... then everything works fine, but you have to rebuild the array in the model in order to unload the data, because stored in the database with id=1.

$form = new TaskForm();

        if (Yii::$app->request->getIsPost()) {
            $form->load(Yii::$app->request->post());
        }


Prompt as it is correct to override checked.

<legend>Категории</legend>
                    <?= $f->field($form, 'categories', [
                        'template' => '{input}{label}'
                    ])->checkboxList($categories, [
                        'item' => function ($index, $label, $name, $checked, $value) use ($categories, $form) {
                            $checked = $checked ? 'checked' : '';
                            return "<input class=\"visually-hidden checkbox__input\" id='{$categories[$index]['id']}' type='checkbox' name='{$name}' value='{$categories[$index]['id']}' $checked>
                                    <label for='{$categories[$index]['id']}'>{$categories[$index]['name']}</label>";
                        }
                    ])->label(false); ?>

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question