php 如何在表单加载时检查 Yii2.0 CheckboxList 项目?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23087963/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:29:20  来源:igfitidea点击:

How to have Yii2.0 CheckboxList items as checked as the form loads?

phpyii2

提问by Cristus Cleetus

I am trying to use a Activeform checkboxlist widget in YII 2.0 Framework

我正在尝试在 YII 2.0 框架中使用 Activeform 复选框列表小部件

in my case, i have an array called "list" which has the names of languages which will be rendered out as checkboxlist, now i am able to do that, but i want the check boxes to be checked as the form loads.

就我而言,我有一个名为“list”的数组,其中包含将呈现为复选框列表的语言名称,现在我可以这样做,但我希望在表单加载时选中复选框。

$list = [0 => 'PHP', 1 => 'MySQL', 2 => 'Javascript'];
$list2 = [0,2];

using the following line, i am able to acheive what i want using HTML helper classes :

使用以下行,我可以使用 HTML 帮助类实现我想要的:

<?= Html::checkboxList('CuisineId',$list2,$list); ?>

but i want to be able to do this using the Activeform Widget CheckboxList, which as per documentationis to be used in the following way :

但我希望能够使用 Activeform Widget CheckboxList 来做到这一点,根据文档,它将以下列方式使用:

static checkboxList( $items, $options = [] )

静态 checkboxList( $items, $options = [] )

So in my case, i have figured how to pass the parameter for $items, which is in the following way:

所以就我而言,我已经想出了如何为 $items 传递参数,方法如下:

<?= $form->field($record, 'CuisineId')->checkboxlist($list);?> 

But now i do not know how to pass the parameters that will allow the checkboxes to be checked.

但是现在我不知道如何传递允许检查复选框的参数。

回答by Cristus Cleetus

Okay i got the solution from yiiframework forumitself.

好的,我从yiiframework 论坛本身得到了解决方案。

The solution was just to add the following line of code and it worked! :

解决方案只是添加以下代码行并且它起作用了!:

$record->CuisineId = $list2;

回答by Андрей Бережков

Solve
database

解决
数据库

view

看法

Controller

控制器

$model = $this->findModel($id);
    $model->INDEXES =ArrayHelper::getColumn($model->publicationIndexes, 'INDEXES_ID');

    if ($model->load(Yii::$app->request->post())) {$model->save();}

View (_form)

查看 (_form)

<?= $form->field($model, 'INDEXES')->checkboxList(ArrayHelper::map(Indexes::find()->all(), 'ID', 'NAME')) ?>