In a nutshell, the task at hand is to mark (or render) a model attribute in the typical "_form.php" view file with the 'required' red asterisk while this attribute is not marked as required in the model's rule() method. If you're interested only in the solution, jump ahead to the 'solution' section below.
Consider the following use case:
public function rules() { return array( array('phone', 'required'), array('phone', 'PcSimplePhoneValidator'), array('fax', 'PcSimplePhoneValidator', 'allowEmpty' => true), //... ); }
We'll change the label rendering method. Change the phone number rendering in _form.php from:
echo $form->labelEx($model, 'phone'); <?php echo $form->textField($model, 'phone', array('size' => 30, 'maxlength' => 30)); <?php echo $form->error($model, 'phone');
to:
echo CHtml::activeLabel($model, 'phone', array('required' => true)); <?php echo $form->textField($model, 'phone', array('size' => 30, 'maxlength' => 30)); <?php echo $form->error($model, 'phone');
As you can see, the only change is the switch from $form->labelEx() to CHtml::activeLabel().
That will render the phone label as 'required' in the same way, with the same CSS class as the rest of our 'required' fields in the form.
Total 2 comments
I think that you're right. I just learned a new thing. Still, masquerading a form label as a required one can be useful in other occasions. Thanks for the input!
If I onderstand your problem correctly, this seems to me like a hacky solution. Use skipOnError instead if you just want to prevent double message. http://www.yiiframework.com/doc/api/1.1/CValidator#skipOnError-detail
Leave a comment
Please login to leave your comment.