0

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.

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

3 Comments

I clarified the problem in my question
Just create an attirbute where to load the array, and then work with it
I had added setter for ingredients and it all worked. Getter was already. With public property also works. Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.