2015-09-09 37 views
0

我有我有2场Product.php型号:Yii2插入同一个表的多个记录

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

我控制器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, 
      ]); 
     } 
    } 

,我想插入多少次相同表与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(); ?> 

但是,当我保存信息的字段被覆盖,只有最后reco rd被插入

回答

6

你要做的是收集,验证和保存表格数据。它不起作用的原因是,在表单中,Yii根据字段名称和模型生成名称标记,例如, name="[Product]["ID_PRODUCT"]。当表单发送到服务器时,第一个字段被最后一个字段覆盖,因为它们具有相同的名称。在表单中收集表格输入的正确方法是在名称末尾添加括号,如下所示; name="[1][Product]["ID_PRODUCT"]。Yii使用这种方法给出了加载和验证多个模型的方法。

修改您的控制器代码以使用多个模型;

<?php 

namespace app\controllers; 

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

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

现在,你拥有所有你需要填充表单,包括你个人情况product模型所产生的任何错误信息的数据。表单的视图文件需要像这样改变,以使用多个模型;

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

所有这一切都被覆盖在Yii2 documentation

相关问题