Answer the question
In order to leave comments, you need to log in
Passing data to form model in Yii2?
Colleagues, such a task:
It is
necessary to create a page with a form for editing the current user
What I have:
There is a table, a model and a controller "User"
Requirements:
There is an ActiveForm form (editUser.php) and a form model (UserEditForm.php)
I need to get the current user in the form (editUser) which uses the UserEditForm model (not the User model).
How to pass this from the controller method to the form so that the corresponding values \u200b\u200bappear in the corresponding fields, but the UserEditForm model is used and it inherits Model (not User)?
PS I always transferred the current model from the controller, unfortunately I did not encounter this case. :(
Answer the question
In order to leave comments, you need to log in
public function actionEditUser($id)
{
$user = User::find()->where('id = :id',[':id' => $id])->one();
if (!$user) {
throw new NotFoundException('User is not found');
}
$model = new EditUserForm;
if ($model->load(Yii::$app->getRequest()->post()) && $model->validate()) {
$user->setAttributes([
'surname' => $model->surname,
'name' => $model->name
]);
$user->save(false); // сохраняем без валидации
return $this->redirect(['editUser', 'id' => $user->id]);
} else {
return $this->render('editUser', ['model' => $model]);
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question