Yii 1.1: an easy way to required multi columns(At least one cannot be blank)

3 followers

in model add the following code:

public function multiItemRequired($attribute,$params)
    {
        if(empty($this->$attribute))
        {
            $required = false;
            $item = explode(',',$params['compare']);
            foreach($item as $attr)
            {
                if(($value = trim($this->$attr)) && !empty($value))
                {
                    $required = true;
                    break;
                }
            }
            if($required === false)
            {
                $field = end($item);
                $this->addError($field,Yii::t('core',$field.' cannot be blank'));
            }
        }
        else
            return;
    }

so you can use like this

public function rules()
    {
        return array(
            ...
            array('field','multiItemRequired','compare'=>'type,title,other'),
            ...
        );
    }

if your rules fields is custom,you must be special a safe rule

...
public $type;
public $title;
public $other;
 
public function rules()
    {
        return array(
            ...
            array('type,title,other','safe'),
            ...
        );
    }
...

also in a scenario

public function rules()
    {
        return array(
            ...
            array('field','multiItemRequired','compare'=>'type,title,other','on'=>'scenario'),
            ...
        );
    }

Be the first person to leave a comment

Please to leave your comment.

Write new article
  • Written by: 1065227709
  • Category: Tips
  • Yii Version: 1.1
  • Votes: +2
  • Viewed: 5,163 times
  • Created on: Aug 18, 2011
  • Last updated: never
  • Tags: rules