Add model validator in Controller

You are viewing revision #3 of this wiki article.
This version may not be up to date with the latest version.
You may want to view the differences to the latest version.

next (#4) »

There are cases that model validators are depended by controller/action and you cannot manipulated 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') {
		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