The first thing to do is to initialize a Model with a scenario. we have two methods to implement it.
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
1 |
$ Model = newMyActiveRecord ('formsubmit '); |
In this example, MyActiveRecord inherits CactiveRecord, and 'fromsumbit 'is a verification scenario.
2. existing CActiveRecord
12 |
$ 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:
123456789 |
Publicfunctionrules () {returnarray (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:
1234567891011121314151617181920212223 |
$ 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.