The scenario is a very useful tool for separating all CModel derived class verification tasks. here we will use CActiveRecord.
The scenario is a very useful tool for separating all CModel derived class verification tasks. here we will use CActiveRecord.
Scenario
The first thing to do is to initialize a Model with a scenario. we have two methods to implement it.
1. the new CActiveRecord uses the constructor's parameter method
$model = new MyActiveRecord('formSubmit');
In this example, MyActiveRecord inherits CactiveRecord, and 'fromsumbit 'is a verification scenario.
2. existing CActiveRecord
$model = MyActiveRecord::model()->find('id = :id', array(':id' => 1); $model->scenario = 'formSubmit';
In this example, we switch the existing model to a scenario.
Create verification rules for the scenario
Note that all verification rules for unspecified scenarios will be used in all scenarios. This will be useful when creating a series of validation rules that do not use inheritance. When the validation rules attributes are set in the model, they are safe unless they are specified in the 'unsafe 'rule. Learn more:
Reference: Model rules validation
Understanding "Safe" Validation Rules
Example of scenario verification rules:
Public function rules () {return array ('name', 'required'), array ('name', 'match', 'not '=> true, 'pattern' => '/[^ a-zA-Z0-9]/', 'message' => 'name must consist of letters, numbers, or spaces ', 'on' => 'formsubmit '),);}
Note that you can use 'on' to specify a rule in a scenario, just as in the example. If no rule name is specified, only the rule name cannot be empty, if 'fromsubmit 'is set, both rules work. Other examples:
$ Model-> scenario = 'formsubmit '; $ model-> name = 'Joe blogs'; if ($ model-> validate ()) {// pass all verifications} $ model-> scenario = 'formsubmit '; $ model-> name = 'Joe Blogs-is awesome !!!! '; If ($ model-> validate () {// do not pass the verification in the scenario 'fromsumbit'} $ model-> scenario = null; $ model-> name = 'Joe Blogs-is awesome !!!! '; If ($ model-> validate () {// The Verification rule is not verified because the scenario is not specified.} $ model-> scenario = 'formsubmit '; $ model-> name = null; if ($ model-> validate () {// verification failed because the verification rule for unspecified scenarios was not passed}
Summary
You can perform cascade verification or independent verification on user input. In this way, you can give users more strict rules in the business logic.