Starite
Starite

Reputation: 71

Yii2 insert multiple records to other table

I want to make a checklist for user to check multiple option. And then when it save, value from checklist go to the "services" tables, the other details go to "post" table. How can I insert multiples record to other tables from just one form. I'm stuck here and I really need helps.

My create function:

 public function actionCreate()
{
    $model = new Posts();
   if ($model->load(Yii::$app->request->post()) && $model->save()) {

        return $this->redirect(['category/index']);
    } else {
        return $this->render('create', [
            'model' => $model,
        ]);
    }
}

My form:

<div class="col-lg-5">
        <?php $form = ActiveForm::begin(['id' => 'station-form', 'options' => ['enctype' => 'multipart/form-data']]); ?>
            <?= $form->field($model, 'name') ?>   
             <?= $form->field($model, 'address') ?>
             <?= $form->field($model, 'phone') ?>
             <?= $form->field($model, 'price') ?>
             <?= $form->field($model, 'square') ?>  
            <?= $form->field($model, 'content')->textarea() ?>
            <?= $form->field($model, 'services_id[]')->checkboxList($items2) ?>

Upvotes: 0

Views: 1983

Answers (1)

Vinai Raj
Vinai Raj

Reputation: 151

If You have two models for

services and post

Given Below that i had done

My _form.php

It Contain Two Models

1.$model for Login details. 2.$condact for contact details.

<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>
    <?= $form->field($model, 'username')->textInput(['maxlength' => true]) ?>
    <?= $form->field($model, 'password')->passwordInput(['maxlength' => true]) ?>
    <?= $form->field($condact, 'name') ->textInput(['maxlength' => true]) ?>   
    <?= $form->field($condact, 'address')->textArea(['rows' => '6']) ?>

My controller

LogindetailsController.php

public function actionCreate()
{
    $model = new Logindetails();
    $condact= new Condactdetails();

    if ( $model->load(Yii::$app->request->post()) && $condact->load(Yii::$app->request->post()) ) {
        $model->save();
        $condact->logid = $model->logid;
        if($condact->save()){
            return $this->redirect(['view', 'id' => $model->logid]);
        }

    } else {
        return $this->render('create', [
            'model' => $model,
        ]);
    }
}

In this way I have Insert into multiple tables. I think This answer will help u to.

Upvotes: 1

Related Questions