Yii2:如何在 CheckboxList 中显示选中的值

Yii2: How to show checked values in CheckboxList

我想在 Yii 2.0 的复选框列表中显示选中的值。以下是我的代码:

主数组:

<?php
$featureArr = array(
    'Change Requester' => 'Change Requester',
    'Clone Request' => 'Clone Request',
    'Suspend Request' => 'Suspend Request',
    'In-Process Requests Open in Edit Mode' => 'In-Process Requests Open in Edit Mode',
    'Allow On-the-Fly Notifications' => 'Allow On-the-Fly Notifications',
    'Additional Comments Field' => 'Additional Comments Field',
    'Do Not Validate Draft Requests' => 'Do Not Validate Draft Requests',
    '(Web-Only) Allow File Attachments' => '(Web-Only) Allow File Attachments',
);

正在从 table 获取数据以显示选中的项目:

$formFeatureModel = FormFeatureForm::find()->where("form_id=" . $model->id)->all();

$checkedFeatureArr = array();
foreach ($formFeatureModel as $data) {
    $checkedFeatureArr[$data->feature] = $data->feature;
}
?>

复选框字段

<?= $form->field(new FormFeatureForm, 'feature')->checkboxList($featureArr, ['class' => 'featureCls']) ?>

我正在从数据库中获取 $checkedFeatureArr 中的选中项。现在我只想显示选中的项目。那么,我应该在哪里传递 $checkedFeatureArr 数组?陷入困境。

如有任何帮助,我们将不胜感激。

当它与模型一起使用时,您应该用选定的值填充 feature 模型 属性。

$model->feature = $checkedFeatureArr;

然后会自动检查。

补充提示:

  • 最好避免在SQL中串联,将->where("form_id=" . $model->id)替换为->where(['form_id' => $model->id])

  • 最好先创建ActiveForm再渲染ActiveField