Yii2 Insert multiple records of a same table

后端 未结 1 1623
花落未央
花落未央 2021-02-06 17:38

I Have my model with 2 fields Product.php:

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

my Controller ProductController.p

1条回答
  •  北荒
    北荒 (楼主)
    2021-02-06 18:15

    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;

    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

    0 讨论(0)
提交回复
热议问题