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

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'),
			...
		);
	}
3 0
3 followers
Viewed: 11 822 times
Version: 1.1
Category: Tips
Tags: rules
Written by: 1065227709
Last updated by: 1065227709
Created on: Aug 18, 2011
Last updated: 13 years ago
Update Article

Revisions

View all history

Related Articles