yii 多记录验证和插入

yii multiple record validate and insert

我想验证并插入单个表单中的多条记录。

我尝试了以下解决方案,但它没有验证每条记录。 Yii - multiple records in one form submission

我在我的表单中使用了类似的东西:

<td><?php echo CHtml::activeTextField($item,"[$i]name"); ?></td>
<td><?php echo CHtml::activeTextField($item,"[$i]price"); ?></td>
<td><?php echo CHtml::activeTextField($item,"[$i]count"); ?></td>
<td><?php echo CHtml::activeTextArea($item,"[$i]description"); ?></td>

在我的控制器中,我做了类似的事情:

public function actionBatchCreate() {
    $models=array();
    // since you know how many models
    $i=0;
    while($i<5) {
        $models[]=Modelname::model();
        // you can also allocate memory for the model with `new Modelname` instead
        // of assigning the static model
    }
    if (isset($_POST['Modelname'])) {
        $valid=true;
        foreach ($_POST['Modelname'] as $j=>$model) {
            if (isset($_POST['Modelname'][$j])) {
                $models[$j]=new Modelname; // if you had static model only
                $models[$j]->attributes=$model;
                $valid=$models[$j]->validate() && $valid;
            }
        }
        if ($valid) {
            $i=0;
            while (isset($models[$i])) {
                $models[$i++]->save(false);// models have already been validated
            }
            // anything else that you want to do, for example a redirect to admin page
            $this->redirect(array('modelname/admin'));
        }
    }

    $this->render('batch-create-form',array('models'=>$models));
}  
<?php
public function actionBatchCreate() 
{

    $arrItems = array();
    $valid = true;

    if(isset($_POST['Modelname'])) {

        foreach ($_POST['Modelname'] as $i => $notUsed)
        {
            $objItem = new Modelname();
            $objItem->attributes=$_POST['Modelname'][$i];

            $valid = $objItem->validate() && $valid;
            $arrItems[] = $objItem;
        }

        if($valid) {
            foreach ($arrItems as $objItemValidated) {
                $objItemValidated->save();  
            }

            $this->redirect(array('modelname/admin'));
        }
    }

    // optional create a initial empty row in View
    if(!count($arrItems)) {
        $arrItems[] = new Modelname();
    }   

    $this->render('batch-create-form',array('models'=>$arrItems));

}  

查看-文件批量创建-form.php

<table>
<?php foreach($models AS $i => $item):?>
    <tr>
        <td><?php echo CHtml::activeTextField($item,"[$i]name"); ?></td>
        <td><?php echo CHtml::activeTextField($item,"[$i]price"); ?></td>
        <td><?php echo CHtml::activeTextField($item,"[$i]count"); ?></td>
        <td><?php echo CHtml::activeTextArea($item,"[$i]description"); ?></td>
    <tr>
<?php endforeach;?>
</table>