I have a table like this: (id, name, version, text). (name, version) is unique key, how can i make a rule to validate this.
They've added support for unique composite keys in the next release candidate of Yii1.14rc, but here's (yet another) solution. BTW, this code uses the same 'attributeName' in the rules that the Yii framework will use in the next official release.
protected/models/Mymodel.php
public function rules()
{
return array(
array('name', 'uniqueValidator','attributeName'=>array(
'name', 'phone_number','email')
),
...
protected/components/validators/uniqueValidator.php
class uniqueValidator extends CValidator
{
public $attributeName;
public $quiet = false; //future bool for quiet validation error -->not complete
/**
* Validates the attribute of the object.
* If there is any error, the error message is added to the object.
* @param CModel $object the object being validated
* @param string $attribute the attribute being validated
*/
protected function validateAttribute($object,$attribute)
{
// build criteria from attribute(s) using Yii CDbCriteria
$criteria=new CDbCriteria();
foreach ( $this->attributeName as $name )
$criteria->addSearchCondition( $name, $object->$name, false );
// use exists with $criteria to check if the supplied keys combined are unique
if ( $object->exists( $criteria ) ) {
$this->addError($object,$attribute, $object->label() .' ' .
$attribute .' "'. $object->$attribute . '" has already been taken.');
}
}
}
You can use as many attributes as you like and this will work for all of your CModels. The check is done with "exists".
protected/config/main.php
'application.components.validators.*',
You may have to add the above line to your config in the 'import' array so that uniqueValidator.php will be found by the Yii application.
Positive feedback and changes are very welcome!