Difference between #6 and #5 of How to use single form to collect data for two or more models (CActiveForm and Ajax Validation edition)

unchanged
Title
How to use single form to collect data for two or more models (CActiveForm and Ajax Validation edition)
unchanged
Category
How-tos
unchanged
Tags
CActiveForm, ajax, several models
changed
Content
With Yii you can use one
[CActiveForm](http://www.yiiframework.com/doc/api/1.1/CActiveForm/) for
collecting data for two or more models with ajax validation and client
validation. 

According [this
article](http://www.yiiframework.com/wiki/19/how-to-use-a-single-form-to-collect-data-for-two-or-more-models)
you can also create a form with ajax validation for both models. 

You have two models $a and $b. 

create.php
~~~
[php]
<?php $form = $this->beginWidget('CActiveForm', array(
    'id'=>'user-form',
    'enableAjaxValidation'=>true,
)); ?>

<?php echo $form->errorSummary(array($a,$b)); ?>

<div class="row">
    <?php echo $form->labelEx($a,'firstName'); ?>
    <?php echo $form->textField($a,'firstName'); ?>
    <?php echo $form->error($a,'firstName'); ?>
</div>
<div class="row">
    <?php echo $form->labelEx($b,'lastName'); ?>
    <?php echo $form->textField($b,'lastName'); ?>
    <?php echo $form->error($b,'lastName'); ?>
</div>

<?php $this->endWidget(); ?>
~~~

controller: 
~~~
[php]
public function actionCreate()
{
    $a=new User;
    $b=new Info;

    $this->performAjaxValidation(array($a,$b));
    if(isset($_POST['User'],$_POST['Info']))
    {
        // populate input data to $a and $b
        $a->attributes=$_POST['User'];
        $b->attributes=$_POST['Info'];
        if($a->save()
        // validate BOTH $a and $b
        $valid=$a->validate();
        $valid=$b->validate() &&
$b->save())$valid;
        
        if($valid)
        {
            // use false parameter to disable validation
            $a->save(false);
            $b->save(false);
            
            $this->redirect('index');
        }
    }
    $this->render('create',array('a'=>$a,'b'=>$b));
}

protected function performAjaxValidation($models)
{
    if(isset($_POST['ajax']) && $_POST['ajax']==='user-form')
    {
        echo CActiveForm::validate($models);
        Yii::app()->end();
    }
}
~~~

Thats all, now you have form with 2 models and ajaxValidation.