Inserting Multiple Models into a Yii2 Form

0

Hello everyone I'm starting on yii2, and I have a question I'm making a form in which I insert two different models into a single form, but I'm not able to do the create: Here is the code I did:

    public function actionCreate()
    {
      $model = new Inscrito();
    $modelEmpresa = new Empresa();     
    if ($model->load(Yii::$app->request->post()) && $model->load(Yii::$app->request->post()) && $modelEmpresa->save() && $modelEmpresa->save()) 
        {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
                'modelEmpresa' => $modelEmpresa,
            ]);
        }
}
    
asked by anonymous 06.06.2016 / 05:01

2 answers

1

In your action, you have to use the methods load () and save () for both classes . In your example, you double-load the same class and save (twice as well) the other. Here is your example, with some changes:

$model = new Inscrito();
$modelEmpresa = new Empresa();
$post = Yii::$app->request->post();

if ($model->load($post) && $modelEmpresa->load($post) && $model->save() && $modelEmpresa->save()) {
    return $this->redirect(['view', 'id' => $model->id]);
}

return $this->render('create', [
    'model' => $model,
    'modelEmpresa' => $modelEmpresa,
]);
    
12.07.2016 / 17:08
0

In this case I would write the code in a different way, using \ yii \ db \ Transaction;

So you can make sure that if one template is not saved the other will not be saved either by doing a ROLLBACK.

    $transaction = \Yii::$app->db->beginTransaction();

    $model = new Inscrito();
    $modelEmpresa = new Empresa();

    try{
        $post = Yii::$app->request->post();
        if($model->load($post) && $model->validate()){
            // ...
            if($modelEmpresa->load($post) && $model->valiedate()){
                $transaction->commit();
            }
        }
    }catch (Exception $e) {
        $transaction->rollBack();
    }
    
23.02.2017 / 01:55