Understanding Scenarios

15 followers

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.

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');

In this example MyActiveRecord extends CActiveRecord and formSubmit is a validation scenario.

2. Pre-existing CActiveRecord instance from find() or other scource

$model = MyActiveRecord::model()->find('id = :id', array(':id' => 1);
$model->scenario = 'formSubmit';

This example is the same as example one except we are switching to a scenario on a pre-existing Model instance.

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'
    ),
  );
}

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:

$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

Conclusion

Now when you validate user inputs you can stratify or separate different input rules on validation. An example of this is wanting to apply more rigid rules to users then to say internal business logic.

Total 3 comments

#8028 report it
tomt92 at 2012/05/04 10:43am
Tip on Dynamic Scenario's

I had to come up with a solution where site admins could change required fields on an input form. so i did the following:

Instead of returning an array of the static rules I set them to a variable.

public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        $rules =  array(
            array('invoice_id, payment_type_id', 'numerical', 'integerOnly'=>true),
            array('line_1, line_2, line_3, line_4, line_5, line_6, line_7, line_8, line_9, line_10', 'length', 'max'=>100),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('id, invoice_id, payment_type_id, line_1, line_2, line_3, line_4, line_5, line_6, line_7, line_8, line_9, line_10', 'safe', 'on'=>'search'),
            array('invoice_id', 'required'),
        );
        $rules = array_merge($rules, $this->findDynamicRules()); 
       return $rules;
    }

This function is called from rule() which looks at the current Scenario and retrieves and builds the necessary rules for that situation. In this case its payment types, and waht lines are required.

private function findDynamicRules(){
        $hold = array();
        $fil = InvoiceBodyPaymentTypePattern::model()->findAll('payment_type_id = :payID', array(':payID'=>$this->scenario));
        $x = 0;
        $str = "";
        foreach ($fil as $row) {
            if ($row->required_yn == 1){
                if($x == 0){
                    $str = 'line_'.$row->line_id;
                    $x++;
                }else{
                    $str .= ', line_'.$row->line_id;
                }
            }
            if($row->filtered_yn == 1){
                array_push($hold, array('line_'.$row->line_id, $row->filter_name));
            }
        }
        if($x != 0){
            array_push($hold, array($str,'required'));
        }
        return $hold;
    }
#5658 report it
l.jurgs at 2011/10/29 06:43am
@dckurushin

Yeah, you're probably right, I just wanted to point out that it is possible to change a scenario once a model is already initialized.

#5657 report it
dckurushin at 2011/10/29 06:32am
best practice

I think it is best to do

$model = new ModelName('scenario');

of course if possible in the specific case you have...

Leave a comment

Please to leave your comment.