Yii2:具有相同按钮的 2 个表单

Yii2: 2 forms with the same button

我想用同一个按钮创建 2 条相同 table 的记录。 table 是:

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`)
) 

这是我的观点_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(); ?>

这是我的控制器的 actionCreate:

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

我需要在 submitButton 中设置 2 个模型,因为当我插入我的字段时,记录是重复的,在这个例子中我插入:

你应该使用表格形式的概念

你的控制器

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

您的观点

<?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(); ?>