Scenarios are an extremely useful tool for separating validation tasks on any class you use derived from CModel. In this tutorial we will use CActiveRecord.
In this example MyActiveRecord extends CActiveRecord and formSubmit is a validation scenario.
This example is the same as example one except we are switching to a scenario on a pre-existing Model instance.
Further Reading:
Reference: Model rules validation
Understanding "Safe" Validation Rules
Note that the rule property that specifies a scenario is 'on' so in this example if there is no scenario then the only rule that applies to name is required. If the Model is set to the scenario 'formSubmit' then the required rule will still apply but so will the match rule.
So to break this down:
Specifying a scenario
The first thing is to initialize the Model instance with a scenario. This can be done one of two ways.1. New CActiveRecord instance with constructor parameter
$model = new MyActiveRecord('formSubmit');
2. Pre-existing CActiveRecord instance from find() or other scource
$model = MyActiveRecord::model()->find('id = :id', array(':id' => 1); $model->scenario = 'formSubmit';
Creating scenario specific validation rules
Firstly it is important to note that any rules not assigned a scenario will be applied to all scenarios. This can be useful for building a pseudo-inheritance structure of rules. Beware however that setting a validator for any property on a model marks it as safe for massive assignments unless the 'unsafe' rule is used.Further Reading:
Reference: Model rules validation
Understanding "Safe" Validation Rules
Example of scenario rules:
public function rules() { return array( array('name', 'required'), array( 'name', 'match', 'not' => true, 'pattern' => '/[^a-zA-Z0-9 ]/', 'message' => 'Name must consist of letters, numbers and spaces only', 'on' => 'formSubmit' ), ); }
So to break this down:
$model = new MyActiveRecord('formSubmit'); $model->name = 'Joe Blogs'; if ($model->validate()) { //this will pass validation as both the required rule and the match rule are satisfied } $model = new MyActiveRecord('formSubmit'); $model->name = 'Joe Blogs - is awesome!!!!'; if ($model->validate()) { //this will fail validation as the match rule is not satisfied } $model = new MyActiveRecord(); $model->name = 'Joe Blogs - is awesome!!!!'; if ($model->validate()) { //this will pass validation as the match rule is no longer checked } $model = new MyActiveRecord('formSubmit'); $model->name = null; if ($model->validate()) { //this will fail validation as the required rule is not satisfied } //Note: the default scenario for CActiveRecord is 'insert' so keep this in mind //when using these examples
No comments:
Post a Comment