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();
}
}