PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, February 16, 2022

[FIXED] Getting an array of checkbox values in the controller

 February 16, 2022     checkbox, yii, yii2     No comments   

Issue

In the form there is such group of checkboxes

$form->field($model, 'ingredients')->checkboxList(
        ArrayHelper::map($ingredients, 'id', 'name')
    )

In html it looks like

<input name="Dish[ingredients][]" value="1" type="checkbox">
<input name="Dish[ingredients][]" value="2" type="checkbox">

How I can get an array of checkboxes values in the actionCreate method of controller?

I trying do it like this

Yii::$app->request->post('Dish[ingredients]', [])

but I get an empty array.

Addition:

Ingredients property is not present in generated model Dish, I'm had added it later by the hand. Dish and Ingredients have a many to many relationship. How to add ingredients to theDish model correctly?

Now if I do

$model = new Dish();
$model->load(Yii::$app->request->post());
var_dump($model->ingredients);

$model->ingredients is empty array.


Solution

Create the ingredients attribute in the Dish model:

public class Dish {
  public $ingredients;
  ...
}

Load all the post data to your model and then access the ingredients array:

$model = new Dish();
$model->load(Yii::$app->request->post());
var_dump($model->ingredients);


Answered By - gmc
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing