Yii 2 ActiveForm表单字段如何实现“全选”?复选框列表中的选项? [英] Yii 2 ActiveForm form field how to implement "select all" option in checkboxlist?

查看:213
本文介绍了Yii 2 ActiveForm表单字段如何实现“全选”?复选框列表中的选项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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}\n{input}\n{hint}\n{error}"])
    ->label(false)
    ->checkboxList($mylist, ['separator' => '<hr>']);
?>

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


推荐答案

1)添加<将a href = http://www.yiiframework.com/doc-2.0/yii-helpers-basehtml.html#checkbox%28%29-detail>复选框添加到您的表单,如下所示:

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,最好使用资产

Then register this js, preferably with assets.

触发点击可用于客户端验证的正确工作如果已启用。

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

这篇关于Yii 2 ActiveForm表单字段如何实现“全选”?复选框列表中的选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆