addErrorClass the Yii way

I was able add an error in my form using addError…however, how should I add error class to the fields that are erroneous?

To the fields or to the Model attributes?



Thanks for the reply Antonio :)

I was already able to do addError, and it is appearing on top of my form…no problem with that.

Aside from the error message on top of the form,and the label of the erroneous field turning red, I want to make the fields have an error class too (turn red on error) so as to be consistent with the whole project.

My field, which is a dropdownlist, does not come from the model but generated from CHtml:

<div class="row">

	<?php echo $form->labelEx($model,'numbers'); ?>


			$numbers =  $model['numbers'];


			$digits = explode('|',$numbers);


				echo CHtml::dropDownList('Winning[digits]['.$x.']', (int)$digits[$x], Type::model()->getNumberOptions($model->type_id));



	<?php echo $form->error($model,'numbers'); ?>


Basically what it does is create 6 successive dropdownlist with IDs starting with Winning_digits(Winning_digits_0,Winning_digits_1, and so on)

And I am manually adding the error class by this:

//part of my controller


 $model->addError('numbers','Winning numbers for this game should not have duplicates');


So that my CHtml-created fields will turn red (The function addJS is just a shortcut for Yii::app()->clientScript->registerScript).

I am just curious if there’s already a way in Yii (aside from what I’ve done) that I can add an error class to the desired fields.

It might help if you use $form->dropDownList() (a wrapper for CHtml::activeDropDownList()) instead of CHtml::dropDownList().

In that case, and if you wish to continue using CHtml::dropDownList instead of active as suggested by BadgerPriest, you could check for the error

 echo CHtml::dropDownList('Winning[digits]['.$x.']', (int)$digits[$x], Type::model()->getNumberOptions($model->type_id), array('class'=>($model->hasErrors('numbers')?'error':'')));

Untested for syntax errors, but should work