When using a model (active record) where the CModel::rules() method has been overridden, and the "required" validator has been applied to any number of attributes, is there a way to easily determine which attributes have been "flagged" as required in the view so that the user is aware of the required field?
For example, I could have an AR class (MyUser) that overrides the rules method like so:
class MyUser extends ActiveRecord .... public function rules() { return array( array('first_name','length','max'=>32), array('last_name','length','max'=>32), array('favorite_color','length','min'=>3), array('first_name,last_name','required'), ); } .... }
Now, in my view I want to flag (using CSS or by placing a "*" next to the label) the fields that were set as required (first_name,last_name) in the AR class, without having to hard code this in to the view. For example, I'm looking for something like this:
<div class="yiiForm"> <?php echo CHtml::form(); ?> <?php echo CHtml::errorSummary($myuser); ?> <div class="simple"> <?php echo CHtml::activeLabel($myuser,'first_name') . ($myuser->isRequired('first_name')?'*':''); ?> <?php echo CHtml::activeTextField($myuser,'first_name',array('size'=>32,'maxlength'=>32)); ?> </div> <div class="simple"> <?php echo CHtml::activeLabel($myuser,'last_name') . ($myuser->isRequired('last_name')?'*':''); ?> <?php echo CHtml::activeTextField($myuser,'last_name',array('size'=>30,'maxlength'=>32)); ?> </div> <div class="simple"> <?php echo CHtml::activeLabel($myuser,'favorite_color') . ($myuser->isRequired('favorite_color')?'*':''); ?> <?php echo CHtml::activeTextField($myuser,'favorite_color',array('size'=>30,'minlength'=>3)); ?> </div> </form> </div>
Obviously I could write my own function in the MyUser class to parse the array returned from rules(), find the attributes that are required, and then return a boolean if the passed in attribute name was in the list. However, it seems that there is already something in the framework that is aware of which attributes are required for validation purposes…I just don't know how to access that intelligence. =)
I apologize in advance if this is a topic covered somewhere – I did try some searching in the docs and forum first. Thanks for the help.