Yii2使用一种形式插入相同模型的多个数据

时间:2019-01-07 10:04:56

标签: yii2 yii2-advanced-app

我正在使用Yii2并尝试以相同的格式插入一个模型的多个数据,就像发票系统以相同的格式插入多个产品一样。

我的视图orm是:

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

    <?= $form->field($model, '[0]studentName')->textInput(['maxlength' => true])->label('NAME') ?>

    <?= $form->field($model, '[0]studentEmail')->textInput(['maxlength' => true])->label('EMAIL') ?>

    <?= $form->field($model, '[0]studentCode')->textInput(['maxlength' => true])->label('CODE') ?>

    <!--  -->

    <?= $form->field($model, '[1]studentName')->textInput(['maxlength' => true])->label('NAME') ?>

    <?= $form->field($model, '[1]studentEmail')->textInput(['maxlength' => true])->label('EMAIL') ?>

    <?= $form->field($model, '[1]studentCode')->textInput(['maxlength' => true])->label('CODE') ?>

    <!--  -->

    <?= $form->field($model, '[2]studentName')->textInput(['maxlength' => true])->label('NAME') ?>

    <?= $form->field($model, '[2]studentEmail')->textInput(['maxlength' => true])->label('EMAIL') ?>

    <?= $form->field($model, '[2]studentCode')->textInput(['maxlength' => true])->label('CODE') ?>

    ....    

    <?= $form->field($model, 'note')->textInput(['maxlength' => true])->label('NOTE') ?>

    <div class="form-group">
        <?= Html::submitButton('Save', ['class' => 'btn btn-success']) ?>
    </div>

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

我的控制器创建动作是:

public function actionCreateClass($ssid)
    {
        $program = new Program();  $model = new ClassC();  $session = $this->findSession($ssid)

        if ($model->load(Yii::$app->request->post())) 
        {
            $program->title = 'PHP'. date('Y') .$session->title;
            $program->note = $model->note;
            $program->save();

            foreach ($model->studentCode as $SC)
            {
                $student = $this->findStudent($SC);

                $model;
                $model->program = $program->program_id;
                $model->save();
            }

            return $this->redirect(['programe', 'id' => $program->program_id]);
        }

        return $this->render('createClass', [
            'model' => $model,
        ]);

我尝试使用var_dump知道返回的内容,但是我的var_dump在var_dump($model)中返回NULL。我也尝试使用

(Model::loadMultiple($model, Yii::$app->request->post()))但出现错误

Call to a member function formName() on array

2 个答案:

答案 0 :(得分:0)

尝试将其放在您的foreach中:

$model->id = NULL; //primary key(auto increment id) id
$model->isNewRecord = true;
$model->program = $program->program_id;
$model->save();

并删除$ model;内循环

答案 1 :(得分:0)

此示例可能会帮助您:

$modelsAddress = [new Address];
$modelsAddress = Model::createMultiple(Address::classname());
Model::loadMultiple($modelsAddress, Yii::$app->request->post());
foreach ($modelsAddress as $modelAddress) {
   $modelAddress->customer_id = $modelCustomer->id;
   $modelAddress->save();
}
  1. 您可以使用createMultiple创建所需模型类的多个实例。
  2. 然后使用loadMultiple从表单中加载数据。
  3. 然后循环浏览所有实例并保存它们。