Difference between #2 and #4 of
How to "masquerade" a non-required form element as 'required' one (in the view only)

Changes

Title unchanged

How to "masquerade" a non-required form element as 'required' one (in the view only)

Category unchanged

How-tos

Yii version unchanged

Tags unchanged

required field, validation rules

Content changed

Problem ------------------ 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:

 
- You have a model with two phone numbers attributes: _phone_ and _fax_. Phone is qa required field while fax is not. Yet, if submitted, both should be validated as 'phone numbers', hence use a custom validator class, [PcSimplePhoneValidator](http://www.yiiframework.com/extension/pcsimplephonevalidator/)). - So, you'rer rules() method will need to look like this:
[...]
PcSimplePhoneValidator that is configured to disallow empty phone numbers (only empty fax is allowed).
- So, you take off the 'required' line in the rules() method above. The line after it will take care that phone is always submitted, and when submitted its validated with our needed validator.
- But, once 'phone' is no more a 'required' attribute in the rules() method, it
's no longer rendered as a required field, taking off the usual red asterisk that followed the label.

The solution
--------
We'll change the label rendering method. Change the phone number rendering in _form.php from:
[...]
5 1
6 followers
Viewed: 25 605 times
Version: 1.1
Category: How-tos
Written by: Boaz
Last updated by: mrun
Created on: Sep 11, 2012
Last updated: 7 years ago
Update Article

Revisions

View all history