Yii2 Insert multiple records of a same table

旧街凉风 提交于 2019-12-03 15:04:26

问题


I Have my model with 2 fields Product.php:

[['ID_PRODUCT'], 'integer'],
[['NAME_PRODUCT'], 'string'],

my Controller ProductController.php:

public function actionCreate()
{
    $model = new Product();

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

And i want insert many times the same table with ActiveForm:

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

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

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

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

    <?= $form->field($model, 'NAME_PRODUCT')->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(); ?>

But when i save the information the fields are overwritten and only the last record is inserted


回答1:


What you are trying to do is collect, validate and save tabular data. The reason it doesn't work is that in the form, Yii generates a name tag based on the field name and model, e.g. name="[Product]["ID_PRODUCT"]. When the form is sent to the server, the first fields get overwritten by the last ones, as they have the same name. The correct way to collect tabular input in a form is to add brackets at the end of the name, like this; name="[1][Product]["ID_PRODUCT"].Using this method, Yii gives ways of loading and validating multiple models.

Modify your controller code to use multiple models;

<?php

namespace app\controllers;

use Yii;
use yii\base\Model;
use yii\web\Controller;
use app\models\Product;

class ProductController extends Controller
{
    public function actionCreate(){

        //Find out how many products have been submitted by the form
        $count = count(Yii::$app->request->post('Product', []));

        //Send at least one model to the form
        $products = [new Product()];

        //Create an array of the products submitted
        for($i = 1; $i < $count; $i++) {
            $products[] = new Product();
        }

        //Load and validate the multiple models
        if (Model::loadMultiple($products, Yii::$app->request->post()) && Model::validateMultiple($products)) {

            foreach ($products as $product) {

                //Try to save the models. Validation is not needed as it's already been done.
                $product->save(false);

            }
            return $this->redirect('view');
        }

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

Now you have all the data you need to populate the form, including any error messages generated for individual instances of you product model. The view file for the form needs to be altered like this, to use the multiple models;

foreach ($products as $index => $product) {
    echo $form->field($product, "[$index]ID_PRODUCT")->label($product->ID_PRODUCT);
    echo $form->field($product, "[$index]NAME_PRODUCT")->label($product->NAME_PRODUCT);
}

All of this is covered in the Yii2 documentation



来源:https://stackoverflow.com/questions/32481399/yii2-insert-multiple-records-of-a-same-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!