Rules can be associated with scenarios. A certain rule will only be used if the model's current scenario
property says it should.
Sample model code:
class User extends CActiveRecord {
const SCENARIO_CHANGE_PASSWORD = 'change-password';
public function rules() {
return array(
array('password, conf_password', 'required', 'on' => self::SCENARIO_CHANGE_PASSWORD),
);
}
}
Sample controller code:
public function actionChangePassword() {
$model = $this->loadModel(); // load the current user model somehow
$model->scenario = User::SCENARIO_CHANGE_PASSWORD; // set matching scenario
if(Yii::app()->request->isPostRequest && isset($_POST['User'])) {
$model->attributes = $_POST['User'];
if($model->save()) {
// success message, redirect and terminate request
}
// otherwise, fallthrough to displaying the form with errors intact
}
$this->render('change-password', array(
'model' => $model,
));
}