One form two models ajax-validation problem

Hey guys,

I have a single form which collects data from two models(due to inheritance). It works fine but the ajax validation is being executed two times - for each of the models that passed as an array arguments. I found such a question in this forum - but the answer to that was not helpful for me. My two models are array($model, $abstract. So when I click on create button, only $model is validated and the $abstract is validated only when i click on the button a second time.

I hope you guys can help me. Here are my code snippets.

1. _form.php snippet:




<?php $form=$this->beginWidget('CActiveForm', array('id'=>'job-form','enableAjaxValidation'=>true,)); ?>



2. create.php snippet:




<?php echo $this->renderPartial('_form', array('model'=>$model, 'abstract'=>$abstract)); ?>



3. Controller(create action) snippet:




public function actionCreate()

{

	$abstract = new AbstractAd;

	$model=new Job;


	$this->performAjaxValidation($model, $abstract);


	if(isset($_POST['Job'], $_POST['AbstractAd']))

	{

	    $abstract->attributes=$_POST['AbstractAd'];

	    $model->attributes=$_POST['Job'];

			

	    if(isset($_POST['Job'], $_POST['AbstractAd']))

	    {

		$abstract->attributes=$_POST['AbstractAd'];

		$model->attributes=$_POST['Job'];

						

		$abstract->user_id=Yii::app()->user->id;

						

		if($abstract->save())

		{

			$model->ad_id = $abstract->id;				

                        if($model->save())

			{

			    $this->redirect(array('view','id'=>$model->id));

			}

			else

			{

			    $abstract->delete();

			}

		}

		   

	}


	$this->render('create',array('model'=>$model, 'abstract'=>$abstract));		

 }



4. Ajax validation in controller changed it to this:




protected function performAjaxValidation($model, $abstract)

{

	if(isset($_POST['ajax']) && $_POST['ajax']==='job-form')

	{

		echo CActiveForm::validate(array($model, $abstract));

		Yii::app()->end();

	}

}



I’ve had the same problem. It is a major problem for me because my service sends out an email after the two models in my form have been validated. So what happens is that two emails are sent out :frowning:

Check your code… you have a duplicate statements ( if(isset($_POST[‘Job’], $_POST[‘AbstractAd’])) )

In your code… you have something like




if( $abstract->save() )

   $model->save()



This way if there is an error in the $abstract $model would not be validated…

You need to use something like




if( $abstract->validate() && $model->validate() )

{

   $abstract->save()

   $model->save()

}