问题
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