php - how to insert data to 2 tables from single form and controller in yii2 -
this 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 field in 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 , crud askquestions table , included class in controller , view page data not inserting in table possible way
the possible solution 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 above code once.
but best solution problem creating , form model same loginform have attributes in single form , validations can applied on in single model. once posted , validated can save values respective models
Comments
Post a Comment