Hi, I’m new with yii2 and now just seriously with update action for multiple select2 in yii2 these below is my code for update action in controller. It doesn’t work, when I update then it created new record . Any recommendation would be appreciated!!
public function actionCreate()
{
$model = new Userdivision();
if ($model->load(Yii::$app->request->post())) {
$uid = $model->user_id;
$array = $model->division_id;
foreach ($array as $key => $var) {
$newModel = new Userdivision();
$newModel->id = $model->id;
$newModel->user_id = $uid;
$newModel->division_id = $var;
$newModel->save(false);
}
return $this->redirect(['index']);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
Where $user_id will be the variable passed as a parameter on the request.
If you do this, when drawing the Select2, the data will be loaded from the model, which is what your are trying to achieve, right?
The update will “break” because of the content in your $model->division_id.
I would change your form, and place these select in a User form, having the User model as the “baseModel” then loading those user divisions with the loadMultiple.
Oh, I got it Sir, thank you so much for your kindly technical support and helping me, it’s really useful and valuable lessons I got from you. I hope to have your advice again next time.
Best regards,