I have a field called ‘Date of Birth’ in my form. So that I can help the user enter their date of birth, I created 3 ‘virtual’ fields for the user to select their date of birth from, as follows:
<div class="row">
<?php echo $form->labelEx($model, 'date_of_birth'); ?>
<?php echo $form->dropDownList($model, 'dob_day', $model->DobDayOptions, array('prompt'=>'Day')); ?>
<?php echo $form->dropDownList($model, 'dob_month', $model->DobMonthOptions, array('prompt'=>'Month')); ?>
<?php echo $form->dropDownList($model, 'dob_year', $model->DobYearOptions, array('prompt'=>'Year')); ?>
<?php echo $form->error($model, 'date_of_birth'); ?>
</div>
As you can see, I retain the ‘label’ and ‘error’ functions of the original field.
In my model I have the following:
array('date_of_birth', 'type', 'type'=>'date', 'dateFormat'=>'yyyy-MM-dd', 'message'=>'{attribute} is invalid or incomplete.'),
public function beforeValidate()
{
if(!empty($this->dob_day) || !empty($this->dob_month) || !empty($this->dob_year))
{
$this->date_of_birth=$this->dob_year."-".$this->dob_month."-".$this->dob_day;
}
return parent::beforeValidate();
}
public function afterValidate()
{
if($this->hasErrors('date_of_birth'))
{
$this->addError('dob_day', '');
$this->addError('dob_month', '');
$this->addError('dob_year', '');
}
return parent::afterValidate();
}
So, just to explain the above:
-
I specify a rule for ‘date_of_birth’ - to say that it must be in the format ‘yyyy-MM-dd’ - this is how MySQL will store the date.
-
In beforeValidate I say that if ANY of those 3 virtual fields have been filled in then we assign a value to ‘date_of_birth’ so that it can be validated.
-
Upon validation if there are any errors with ‘date_of_birth’ then we add an error to the three virtual fields.
In non-ajax validate mode this all works as expected. However when I change to ajaxValidation, the following occurs:
-
The ‘date_of_birth’ label is not highlighted in red
-
The 3 virtual fields are not highlighted in red
-
The correct error message is however displayed
What seems to be happening is that the field’s container div is not getting the “error” class appended to it.