简体   繁体   中英

Yii same model saved twice, AJAX Validation

I need to save model twice with different data:

Controller:

 $modelClient = new Client;

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

View (only relevant part of it)

<?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"]}

So the second model is just ignored.

I tried

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

but it returns JSON Output without the right id, eg.:

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

and as a result it just doesnt validate any of fields.

In your controller you should declare the models as array.

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

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

And your first model goes to $modelClients[0] and second model to $modelClients[1]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM