Hima Naga Uday Kiran
Hima Naga Uday Kiran

Reputation: 31

how to insert data to 2 tables from single form and controller in yii2

this is my create page

questions/create.php

<?php $form = ActiveForm::begin(); ?>
<br><br><br>
<?= $form->field($model, 'question')->textInput(['maxlength' => true]) ?>

<?= $form->field($model, 'topic')->textInput(['maxlength' => true]) ?>
<?= $form->field($model1, 'askid')->textInput(['maxlength' => true]) ?>

 <div class="form-group">
  <?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Create') :   Yii::t('app', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
  </div>

<?php ActiveForm::end(); 

askid is the field in another table askquestions

questioncontroller

public function actionCreate()
{
    $model = new Questions();
    $model1 = new Askquestions();

     //$model1 -> load(Yii::$app->request->post());



    if ($model1->load(Yii::$app->request->post())) {
        //$model->user_id=Yii::$app->user->identity->id;
         if($model1->save())
        return $this->redirect(['index']);
     } else {
        return $this->render('create', [
            'model' => $model, 'model1' => $model1,
        ]);
    }
   }

i have generated model and crud for askquestions table and also included class in the controller and view page but the data is not inserting in the table what would be the possible way

Upvotes: 0

Views: 2190

Answers (1)

Chetan Sharma
Chetan Sharma

Reputation: 2557

The possible solution would be: (not tested)

public function actionCreate()
{
    $model = new Questions();
    $model1 = new Askquestions();

    if ($model->load(Yii::$app->request->post()) && $model1->load(Yii::$app->request->post())) {
        //$model->user_id=Yii::$app->user->identity->id;
         if($model->save() && $model1->save())
        return $this->redirect(['index']);
     } else {
        return $this->render('create', [
            'model' => $model, 'model1' => $model1,
        ]);
    }
   }

Try the above code once.

But the best Solution for this problem will be creating and Form Model same like LoginForm it will have all the attributes in single form and validations can be applied on in single model. Once everything is posted and validated then you can save the values to the respective models

Upvotes: 1

Related Questions