问题描述
Yii 2 ActiveForm 表单域如何实现复选框列表中的全选"选项?
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}
{input}
{hint}
{error}"])
->label(false)
->checkboxList($mylist, ['separator' => '<hr>']);
?>
<?= Html::submitButton('submit', ['class' => 'btn btn-primary']) ?>
<?php ActiveForm::end();
?>
推荐答案
1) 添加 checkbox 到您的表单中,如下所示:
1) Add checkbox to your form like so:
echo Html::checkbox(null, false, [
'label' => 'Check all',
'class' => 'check-all',
]);
2) 添加一些 javascript 以使其工作:
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');
});
});
将 #root-container-id
替换为该字段的容器的实际 ID.它应该类似于型号名称 + 破折号 + MENU_DESC.在生成的 html 输出中查看它.或者您可以添加另一个类或构建选择器的名称为复选框,这取决于您.
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.
然后注册这个js,最好用assets.
Then register this js, preferably with assets.
如果启用,触发点击用于客户端验证的正确工作.
Triggering click is used for correct work of client validation if it's enabled.
这篇关于Yii 2 ActiveForm 表单域如何实现“全选"复选框列表中的选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!