Yii2 two models, two views, two tables

62 Views Asked by At

I'm just learning a little bit how to use the framework Yii2. Now I have a specific question.

I have 2 models, 2 views and 2 tables. View 1 always appears and view 2 only when a condition in form 1 was met.

$model_user = new User();
$model_details = new Details();

Is there any way to save both models together after view 2 is filled? Currently I have the problem that the data in $model_user (view 1) is reset as soon as I submit view 2 ($model_details).

Thanks a lot!

1

There are 1 best solutions below

0
WeSee On

An example for a controller action could be:

public function actionView2() 
{
    $model_user = new User();
    $model_details = new Details();
    if ($model_user->load(Yii::$app->request->post())
      && $model_details->load(Yii::$app->request->post()))
    {
        if ($model_user->save()
          && model_details->save()) 
        {
            return $this->redirect(['index']);
        }
    }
    return $this->render('view2', [
        'model_user' => $model_user,
        'model_details' => $model_details,
    ]);
}

In this action you fill both models and save it to the database. The best: The models are only saved to the database if the rules match. So, if the user enters something incorrect, the models are not saved to the database. See here