Yii2 Insert multiple records of a same table

十年热恋 提交于 2019-12-03 03:58:37
Joe Miller

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

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