Answer the question
In order to leave comments, you need to log in
Is it necessary to create models for forms in yii2?
This question has been tormenting for a long time, was it worth creating, for example, a Singup model (like this one ), if you can use the main User model:
public function actionSignup()
{
if (!Yii::$app->user->isGuest) {
return $this->goHome();
}
$model = new User();
if ($model->load(Yii::$app->request->post())) {
$model->setPassword($model->password);
if ($model->save()) {
if (Yii::$app->getUser()->login($model)) {
return $this->goHome();
}
}
}
return $this->render('signup', [
'model' => $model,
]);
}
public function actionSignup()
{
$model = new SignupForm();
if ($model->load(Yii::$app->request->post())) {
if ($user = $model->signup()) {
if (Yii::$app->getUser()->login($user)) {
return $this->goHome();
}
}
}
return $this->render('signup', [
'model' => $model,
]);
}
Answer the question
In order to leave comments, you need to log in
- Forms are more portable and reusable
- Forms may not be tied to model attributes and better express the subject area
- Forms are easier to test
- Using forms is easier to develop in a team
- Validation in models violates SOLID principles (AR violates them in principle, but at least this part can be leveled)
- For elementary CRUD with minimal business logic, you can do without, but if a lot of logic is tied to the model and the scripts grow, the model will quickly turn into a divine object
- Sculpting all validations into one form-model is no better than sculpting them in Ap-model -> for each case a separate model-shape
--------------------
Summary:Use validation on scripted models until you understand what forms are for. Use for the sake of use, without awareness - is still meaningless and merciless
Models are just thin AR classes with no validation attributes.
Forms are input and validation.
Use the SRP principle, forms should validate data, the AR entity should store just fields.
not for "specific purposes", but for forms. yes, it is necessary.
I don’t remember what exactly was pathetic when there was no form model during registration, but something was definitely pathetic.
but if everything is in order for you, then for now limit yourself to User, then transfer it if anything.
was it worth creating, for example, the Singup model
$model = new User;
$model->scenario = User::SCENARIO_LOGIN;
$model = new User;
$model->scenario = User::SCENARIO_REGISTER;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question