Inserting multiple templates in a Yii2 form

Asked

Viewed 262 times

0

Hello Everyone I am starting in yii2, and I have a question I am making a form in which I insert two different models in a single form, but I am not able to perform create: Follow the code I made:

    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,
            ]);
        }
}

2 answers

1

In your action, you have to use the methods load() and save() for both classes. In your example, you load twice in one class and save (twice also) in the other. Follow 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,
]);

0

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

This way you can ensure that if one model is not saved the other will also not be saved by performing 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();
    }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.