Workonphp
Workonphp

Reputation: 1675

Confusion with validation rules in Yii framework

I am new to Yii framework & having some confusion regarding validation rules which are written inside model. For ex:
array('email','safe'),
array('username, password', 'required', 'on'=>'login, register'),

1- what is the use of safe validator & where to use it?
2- what is the use of on scenario and how to use it? Suppose I have wriiten 'on'=>'register', then whether 'register' is action name or anything else.

Even after going through lots of document, still it is not very clear for me. Can someone explain it with example.

Upvotes: 0

Views: 2896

Answers (2)

user1233508
user1233508

Reputation:

what is the use of safe validator & where to use it?

safe validator can be used to indicate "this field can accept anything and no validation should be performed". It's relevant during mass-assignment:

$model->attributes = $_POST['Model'];

If the field has no rules set, its value will not be updated after this assignment. If a field does not require any validation, but should still be updated in this case, you can use the safe rule to indicate this (but be careful with that, validation is a good thing).


what is the use of on scenario and how to use it? Suppose I have wriiten 'on'=>'register', then whether 'register' is action name or anything else.

In this case, register is a scenario (an arbitrary string of your choice, describing what is happening to the model). You assign the model's scenario in the controller, before performing mass assignment and other work. When the time comes to validate the model, Yii will look at the model's scenario property and run the validators based on that. (In a reasonably sized project, you will want to use class constants instead of arbitrary strings for consistency.)

Example: user password change. You can set up the following validator to mark the password field as required only in this scenario, and not otherwise:

// validator in the model class
array('password', 'required', 'on' => 'change-password'),

// code in the right controller's action
$user->scenario = 'change-password'; // set the scenario
$user->attributes = $_POST['User'];
$user->validate(); // if the password is not set, this will result in a validation error

Look at this answer for some more information and links to further reading.

Upvotes: 5

Vainglory07
Vainglory07

Reputation: 5283

Have you read the following articles?

http://www.yiiframework.com/wiki/56/

http://www.yiiframework.com/wiki/161/understanding-safe-validation-rules/

Safe Marks the associated attributes to be safe for massive assignments. On keyword specifies scenarios like login, registration

Upvotes: 0

Related Questions