Add model validator in Controller

You are viewing revision #4 of this wiki article.
This is the latest version of this article.
You may want to see the changes made in this revision.

« previous (#3)

There are cases that model validators should be depended by controller/action and you couldn't manipulate on the model class or using scenarios in easy way

For example, when inserting a new record we want the controller/action to deside whether or not a validator (or more than one) should be applied.

So a robust way to do that is by insert a validator to the model on Controller/action

For example

class MyUser extends CActiveRecord {
 
 public function rules() {
	array('user,email,password', 'required', 'on' => 'insert'),
	array('user,email,password,city,postcode','length', 'min' => 4, 'max' => 15),
 }
 
}

In Controller/action

function actionCreateUser($type) {
$model = new MyUser();
...
if ($type=='company') {
	$model->validatorList->add(
		CValidator::createValidator('required', $model, 'city,postcode')
	);
}
.... now set massive data,validate and save
}

PS: You could check the type of user on beforeValidate Model method adding a validator conditionally but in fact is more easy and more MVC-way to do that in controller.

Why ? If we add this condition to the model we give to the Model more logic task. But MVC should have more seperated role for Model Viewer and Controller and not overloaded micro-conception MVC architecture

see this article to get another real issue what exactly I mean http://www.yiiframework.com/forum/index.php/topic/43999-activate-a-captcha-after-of-several-times/