Answer the question
In order to leave comments, you need to log in
How to correctly pass the selection of a dropdownlist multiselect to write to the database in yii2?
Hello! I have a form with a droplist multiselect
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'dtitle')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'parts')->dropDownList($model->IngredientDropdown,
[
'multiple' => 'multiple'
]
); ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Добавить' : 'Редактировать', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
public function getIngredientDropdown()
{
$listIngredient = Ingredient::find()->select('id,ititle')->all();
$list = ArrayHelper::map( $listIngredient, 'id', 'ititle');
return $list;
}
public function actionCreate()
{
$model = new Dish();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
$model->parts = implode(",", $_POST['parts']);
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
Answer the question
In order to leave comments, you need to log in
Those. In fact, you want that when submitting the form, the data would be saved to the associated table along with saving the model? If so, then you are reinventing the wheel. Read this article on habré
1. if the choice is multiple, then change
to
2. here:
if ($model->load(Yii::$app->request->post()) && $model->save()) {
$model->parts = implode(",", $_POST['parts']);
But it gives the error "The value of 'Parts' is invalid".There is no such error, give an example of a real error. Although it will go away if you fix the above. By the way, in the rules of the model, make it safe for parts, since this is an array and will not be validated.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question