"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


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

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


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()) {
    } else {
        if ($isblacklist) $model->addError('text_user_input','Are you an ambitious hacker eh?');


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
Viewed: 36 604 times
Version: Unknown (update)
Category: How-tos
Last updated by: brianvu
Created on: Jul 13, 2013
Last updated: 7 years ago
Update Article


View all history

Related Articles