Yii 2 ActiveForm form field how to implement “select all” option in checkboxlist?

我们两清 提交于 2019-12-07 17:56:55

问题


Yii 2 ActiveForm form field how to implement "select all" option in checkboxlist?

<?php
$form = ActiveForm::begin([
    'id' => 'form-id',
    'type' => ActiveForm::TYPE_HORIZONTAL,
    'options' => ['class' => 'well'],   
]);
?>

<?php
    echo $form->field($model, 'MY_DESC', ['template' => "{label}\n{input}\n{hint}\n{error}"])
    ->label(false)
    ->checkboxList($mylist, ['separator' => '<hr>']);
?>

<?= Html::submitButton('submit', ['class' => 'btn btn-primary']) ?>
<?php ActiveForm::end();
?>

回答1:


1) Add checkbox to your form like so:

echo Html::checkbox(null, false, [
    'label' => 'Check all',
    'class' => 'check-all',
]);

2) Add some javascript to get it to work:

$('.check-all').click(function() {
    var selector = $(this).is(':checked') ? ':not(:checked)' : ':checked';

    $('#root-container-id input[type="checkbox"]' + selector).each(function() {
        $(this).trigger('click');
    });
});

Replace #root-container-id with the actual id of your container for that field. It should be something like Model name + dash + MENU_DESC. See it in generated html output. Or you can add another class or build selector with name of checkbox, it's up to you.

Then register this js, preferably with assets.

Triggering click is used for correct work of client validation if it's enabled.



来源:https://stackoverflow.com/questions/28059193/yii-2-activeform-form-field-how-to-implement-select-all-option-in-checkboxlist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!