问题
I want to show checked values in my checkboxlist in Yii 2.0. Following is my code:
Main Array:
<?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',
);
Getting data from table to display checked items:
$formFeatureModel = FormFeatureForm::find()->where("form_id=" . $model->id)->all();
$checkedFeatureArr = array();
foreach ($formFeatureModel as $data) {
$checkedFeatureArr[$data->feature] = $data->feature;
}
?>
Checkbox field
<?= $form->field(new FormFeatureForm, 'feature')->checkboxList($featureArr, ['class' => 'featureCls']) ?>
I am getting checked item in $checkedFeatureArr
from database. Now I just want to show checked items. So, Where should I pass $checkedFeatureArr
array? Getting stuck in this.
Any help would be appreciated.
回答1:
When using it with model, you should fill feature
model property with selected values instead.
$model->feature = $checkedFeatureArr;
Then it will be checked automatically.
Additional tips:
It's better avoid concatenation in SQL, replace
->where("form_id=" . $model->id)
with->where(['form_id' => $model->id])
.It's better create
ActiveForm
before renderingActiveField
.
来源:https://stackoverflow.com/questions/29888665/yii2-how-to-show-checked-values-in-checkboxlist