unique-attributes-validator Validate unique constraints with more then one attribute

  1. Requirements
  2. Usage
  3. Resources

Yii comes with bucket of validators including a unique validator which validates whether an attribute value is unique in the corresponding database table. But what if your database unique constraint contains more than one attribute?

I have seen a couple Yii extensions which solve the problem but none of them are using the built-in CUniqueValidator parts. There are two ways to solve the validation problem, the first one is to add some criteria to the unique validator:

public function rules() {
    return array(
        array('firstKey', 'unique', 'criteria'=>array(
            'condition'=>'`secondKey`=:secondKey',
            'params'=>array(
                ':secondKey'=>$this->secondKey
            )
        )),
    );
}

That will do the trick, however it can get a bit cleaner. The UniqueAttributesValidator does this for you:

public function rules() {
    return array(
        array('firstKey', 'UniqueAttributesValidator', 'with'=>'secondKey'),
    );
}

The UniqueAttributesValidator uses parts of CUniqueValidator and extends it by adding certain criteria. It also works for unique constraints with N attributes:

public function rules() {
    return array(
        array('firstKey', 'UniqueAttributesValidator',
                      'with'=>'secondKey,thirdKey,...'),
    );
}

Requirements

Yii 1.0 or above

Usage

public function rules() {
    return array(
        array('firstKey', 'UniqueAttributesValidator',
                      'with'=>'secondKey,thirdKey,...'),
    );
}

Resources

8 0
23 followers
2 248 downloads
Yii Version: 1.1
License: BSD-2-Clause
Category: Validation
Developed by: Tijnos
Created on: Feb 17, 2012
Last updated: 12 years ago

Downloads

show all

Related Extensions