"safe" and "unsafe" Model validators (massive assignments)

You are viewing revision #11 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 or see the changes made in this revision.

« previous (#10)next (#12) »

Ok, it is a little bit difficult to full understanding the unsafe validator.

User inputs that have not at least one validator in model will be rejected

So why the 'unsafe' validator is useful and when ?

Suppose You have an attribute in Model (CActiveRecord) that has to be saved (in most cases)

So the rule for this attribute should be

array('text_user_input', 'safe'), //or any other usual validator

Suppose also you have a blacklist users whom you want to prevent to pass their inputs. How to achieve that? A solution is using the unsafe validator

array('text_user_input', 'unsafe', 'on'=>'blacklistuser'),

I give you an example with code to make it cleaner

model:

class Article extends CActiveRecord {
...
array('text_user_input', 'safe'),
array('text_user_input', 'unsafe', 'on'=>'blacklistuser'),
...
}

viewer: //nothing extra, gii generated all the stuffs

controller:

public function actionNewArticle() {
       if (Yii::app()->user->id == '13' ) { //as example
          $model = new Article('blacklistuser');
          $isblacklist = true;
      } else {
        $model = new Article;
        $isblacklist = false;
     }

if (isset($_POST['Article'])) {
    $model->attributes = $_POST['Article'];
    if ($model->validate()) {
       $model->save(false)
    } else {
        if ($isblacklist) $model->addError('text_user_input','Are you an ambitious hacker eh?');
    }
}

     $this->render('create',array('model'=>$model));
 }

note: the first rule matches and save the attribute (for all cases even for blacklistuser scenario) but the second one overrides the first and assigns as unsaved this attribute. also κeep in mind the order of the rules is irrelevant.

2 2
7 followers
Viewed: 37 146 times
Version: Unknown (update)
Category: How-tos
Last updated by: brianvu
Created on: Jul 13, 2013
Last updated: 8 years ago
Update Article

Revisions

View all history

Related Articles