Extension for CUniqueValidator

Hi guys,

I was working on the following problem: I wanted an attribute to be unique in a table, but only within a group of th e same id’s.

Example: in a table (id, foreign_key, name), name should be unique within a group of rows with the same foreign key.

I didn’t really find a clean way to do it, so I ‘hacked’ it into CUniqueValidator like this.


if($this->criteria!==array()) {

	$customCriteria = $this->criteria;

	if(isset($customCriteria['params'])) {

		foreach($customCriteria['params'] as $k => $v) {

			if($v != null) continue;


			if(($column=$table->getColumn($k))===null)

				throw new CException(Yii::t('yii','Column "{column} does not exist in table "{table}".',

					array('{column}'=>$k,'{table}'=>$table->name)));

			else $customCriteria['params'][$k] = $object->$k;

		}

	}

	$criteria->mergeWith($customCriteria);

}

and you use it by putting something like this in your Model:


array('name', 'unique', 'criteria' => array(

	'condition' => 'foreign_key = :foreign_key',

	'params' => array('foreign_key' => null)

)),

So what do you think? Anyone with a better idea on how to handle this?

If possible I’d like to see something like this in a future Yii release (I prefer to have my local copy not to differ too much from the official release)

Thanks,

Javache

An alternative (cleaner?) fix


/**

 * @var array a list of extra parameters to bind from the model

 */

public $bindParams=array();


foreach($this->bindParams as $param)

{

	if(($column=$table->getColumn($param))===null)

		throw new CException(Yii::t('yii','Column "{column} does not exist in table "{table}".',

			array('{column}'=>$param,'{table}'=>$table->name)));

	$criteria->mergeWith(array(

		'params' => array(':'.$param=> $object->$param)

	));

}

There is a thread that has a related problem here.