Yii2: How to show checked values in CheckboxList
I want to show checked values in my checkbox list in Yii 2.0. Below 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',
);
Retrieving data from a table to display selected items:
$formFeatureModel = FormFeatureForm::find()->where("form_id=" . $model->id)->all();
$checkedFeatureArr = array();
foreach ($formFeatureModel as $data) {
$checkedFeatureArr[$data->feature] = $data->feature;
}
?>
Check box
<?= $form->field(new FormFeatureForm, 'feature')->checkboxList($featureArr, ['class' => 'featureCls']) ?>
I am getting the check item in $checkedFeatureArr
from the database. Now I just want to show the checked items. So where do I pass the array $checkedFeatureArr
? Stuck in this.
Any help would be appreciated.
source to share
When using it with a model, you must populate the model property with the feature
selected values.
$model->feature = $checkedFeatureArr;
Then it will be automatically checked.
Additional tips:
-
Better to avoid concatenation in SQL, replace
->where("form_id=" . $model->id)
with->where(['form_id' => $model->id])
. -
Better to create
ActiveForm
before renderingActiveField
.
source to share