Yii同样的模型保存了两次,AJAX验证

时间:2012-05-23 13:59:57

标签: php ajax validation yii

我需要使用不同的数据保存模型两次:

控制器:

 $modelClient = new Client;

 if(Yii::app()->getRequest()->getIsAjaxRequest()) {
    echo CActiveForm::validateTabular( array( $modelClient));
    Yii::app()->end();
 }

查看(仅相关部分)

<?php echo $form->textFieldRow($modelClient, '[0]name'); ?>
<?php echo $form->textFieldRow($modelClient, '[0]street'); ?>

<?php echo $form->textFieldRow($modelClient, '[1]name'); ?>
<?php echo $form->textFieldRow($modelClient, '[1]street'); ?>

JSON OUTPUT

{"Client_0_name":["field is empty"],"Client_0_street":["field is empty"]}

所以第二个模型被忽略了。

我试过

if(Yii::app()->getRequest()->getIsAjaxRequest()) {
   foreach ($_POST[Client] as $client) {
    $temp = new Client;
    $temp->setAttributes($client);
    echo CActiveForm::validate( array( $modelClient));
   }
   Yii::app()->end();
}

但它返回没有正确id的JSON输出,例如:

 {"Client_name":["field is empty"],"Client_street":["field is empty"]}

因此它不会验证任何字段。

1 个答案:

答案 0 :(得分:1)

在控制器中,您应该将模型声明为数组。

 $modelClients=array();
 $modelClients[] = new Client;
 $modelClients[] = new Client;

 if(Yii::app()->getRequest()->getIsAjaxRequest()) {
    echo CActiveForm::validateTabular(  $modelClients);
    Yii::app()->end();
 }

您的第一个模型转到$modelClients[0],第二个模型转到$modelClients[1]