The form has a dropDownList for outputting data from the database as a drop-down list with multiple choices:

<?= $form->field($model, 'parts[]')->dropDownList($model->IngredientDropdown, ['multiple' => 'multiple'] ); ?> 

In the model:

 public function getIngredientDropdown() { $listIngredient = Ingredient::find()->select('id,ititle')->all(); $list = ArrayHelper::map( $listIngredient, 'id', 'ititle'); return $list; } 

In the controller:

  public function actionCreate() { $model = new Dish(); if ($model->load(Yii::$app->request->post()) && $model->save()) { return $this->redirect(['view', 'id' => $model->id]); } else { return $this->render('create', [ 'model' => $model, ]); } } 

I ask to prompt how to save the selected data in the form of one entry separated by commas in the parts field in the parts field?

    1 answer 1

    Just before saving you need to convert the array to a string, you can do it with the implode () function

     public function actionCreate() { $model = new Dish(); if ($model->load(Yii::$app->request->post())) { $model->parts = implode(',', $model->parts); if ($model->save()) { return $this->redirect(['view', 'id' => $model->id]); } } return $this->render('create', [ 'model' => $model, ]); } 

    Before outputting to the form for editing the model, it is necessary to convert the string into an array using the explode () function .

     public function actionUpdate() { $model = Dish::findOne($id); $model->parts = explode(',', $model->parts); if($model->load(Yii::$app->request->post())) { $model->parts = implode(',', $model->parts); if ($model->save()) { return $this->redirect(['view', 'id' => $model->id]); } } return $this->render('update', [ 'model' => $model, ]); }