I want to checked Yii2 CheckboxList at time of post update my list of options is mention below
<?= $form->field($category,'title')->checkboxList([1=>'Latest news','2'=>'Unit Performance','3'=>'Latest Technology'])->label(FALSE); ?>
I want to check some item at time of update which is selected at the time of post creation like latest news
.
Kindly help me
Use line of code of example.
$list = [1=>'Latest news','2'=>'Unit Performance','3'=>'Latest Technology'];
<?= $form->field($category,'title')->checkboxList($list)->label(FALSE); ?>
If option "Latest news" and "Unit Performance" is selected so, on update selected option value array will be $checkedList = [1, 2];
So, Simply assign $checkedList
array to $category->title
. Like as,
$category->title = $checkedList;
Full example is:
$list = [1=>'Latest news','2'=>'Unit Performance','3'=>'Latest Technology'];
if(!$category->isNewRecord) {
$checkedList = [1, 2]; //get selected value from db if value exist
$category->title = $checkedList;
}
<?= $form->field($category,'title')->checkboxList($list)->label(FALSE); ?>
You can use the following code to get array of selected checkboxes.
$selected_checkbox_array = Yii::$app->request->post("title");
Here if you would like to concat them into string, you can use php's implode function
$selected_checkboxes = implode(',', $selected_checkbox_array);
Other way is
if ($model->load(Yii::$app->request->post()))
{
$model->title= implode(",", $model->title);
if($model->save())
{
return $this->redirect(['gridpage', 'id' => $model->id]);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.