简体   繁体   中英

Yii2 two models, two views, two tables

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM