mhplur
mhplur

Reputation: 218

Yii2: 2 forms with the same button

I want create 2 records of same table with the same button. The table is:

CREATE TABLE `consecuencia` (
 `ID_CONSECUENCIA` int(11) NOT NULL AUTO_INCREMENT,
 `VALOR_CAT_CONSECUENCIA` varchar(1024) NOT NULL,
 `ESTADO` varchar(3) NOT NULL,
 PRIMARY KEY (`ID_CONSECUENCIA`)
) 

And this is my view _form.php

 <?php $form = ActiveForm::begin(); ?>
    //FIRST RECORD
    <?= $form->field($model, 'VALOR_CAT_CONSECUENCIA')->textInput(['maxlength' => true]) ?>
    <?= $form->field($model, 'ESTADO')->textInput(['maxlength' => true]) ?>
    //SECOND RECORD
     <?= $form->field($model1, 'VALOR_CAT_CONSECUENCIA')->textInput(['maxlength' => true]) ?>
    <?= $form->field($model1, 'ESTADO')->textInput(['maxlength' => true]) ?>

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

    <?php ActiveForm::end(); ?>

this is my actionCreate of my Controller:

public function actionCreate()
    {
        $model = new Consecuencia();
        $model1 = new Consecuencia();
        if ($model->load(Yii::$app->request->post()) && $model1->load(Yii::$app->request->post())
            && $model->save() && $model1->save()) {
            return $this->redirect(['view', 'id' => $model->ID_CONSECUENCIA]);
        } else {
            return $this->render('create', [
                'model' => $model,
                'model1' => $model1,
            ]);
        }
    }

I need the way to set 2 models inside the submitButton because when i insert my fields the records is duplicated, in this example i insert:

enter image description here

Upvotes: 2

Views: 962

Answers (1)

ck_arjun
ck_arjun

Reputation: 1417

You should use tabular form concept

Your controller

use yii\base\Model;

public function actionCreate()
{
    for( $i = 0;$i <2;++$i){
          $models[] = new Consecuencia();
    }
    if (Model::loadMultiple($models,yii::$app->request->post() ) &&
               Model::validateMultiple($models)){
        foreach($models as $model){ 
             $model->save();
        }
        return $this->redirect(['view', 'id' => $model->ID_CONSECUENCIA]);
    } else {
        return $this->render('create', [
            'models' => $models
        ]);
    }
}

Your View

<?php $form = ActiveForm::begin(); ?>

<?php foreach($models as $key => $model) {

      <?= $form->field($model, "[$key]VALOR_CAT_CONSECUENCIA")->textInput(['maxlength' => true]) ?>
      <?= $form->field($model, "[$key]ESTADO")->textInput(['maxlength' => true]) ?>


<?php } ?>

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

<?php ActiveForm::end(); ?>

Upvotes: 1

Related Questions