Home » Php » php – checking checkboxList in Yii2 at the time of updating post?

php – checking checkboxList in Yii2 at the time of updating post?

Posted by: admin July 12, 2020 Leave a comment

Questions:

I want to checked Yii2 CheckboxList at time of post update
my list of options is mention below
enter image description here

<?= $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 .

enter image description here

Kindly help me

How to&Answers:

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); ?>

Answer:

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]);
       }    
}