Scenarios validation is the one of the useful future in yii framwork and seperating the validation on any class derived from CModel. For example When we register a user, we will do some validation. For the registered user update, we will use different type validation. In this type of case we will use scenario.
Syntax
//rule for single scenario
'on'=>'scenarioName'
//rule for multiple scenarios
'on'=>'scenarioName_1, scenarioName_2, scenarioName_3'
Secnarios validation is used to restrict the data When we apply this.
CActiveRecord Scenarios
By default CActiveRcord having three scenarios. Thet are insert, update and search. When we create a new record in database table, the 'insert' scenario will automatically work. When we update a record, the model will take 'update' scenario. Scenatio is a very useful way to validate the model in different types of method.
Scenario With Default Validation
public function rules()
{
..............
array('createdon', 'default',
'value'=>new CDbExpression('NOW()'), 'on'=>'insert'),
array('updatedon', 'default',
'value'=>new CDbExpression('NOW()'), 'on'=>'update'),
array('id, username, email', 'safe', 'on' => 'search'),
..............
}
Scenario With Required
public function rules()
{
..............
array('username, email', 'required','on'=>'register'),
..............
}
Scenario With Password Validation
Password scenario will helpful to understand the use of scenario in model. I given sample user model. Normally when we register a user model, we will give the username, password, firstname etc and also we will change the password simultensiouly. For this i added the scenario validation below
User Model
class ClassName extends CActiveRecord
{
..............
public function rules() {
..............
array('password', 'compare', 'compareAttribute' =>'confirmpassword',
'on'=>'register,changepassword'),
array('username, email', 'unique','on'=>'register, update'),
..............
}
..............
}
Validation Scenario In Controller
I added the different type format for same scenario validation in controller action.
<?php
...............
public function actionRegister(){
$model=new User;
$model->scenario='register';
// OR
//$model=new User('register');
// OR
//$model=new User();
//$model->validate('register');
}
public function actionChangepassword($id){
$model=new User;
$model->scenario='changepassword';
// OR
//$model=new User('changepassword');
//$model=new User();
//$model->validate('changepassword');
}
?>