Custom Yii Rule for Unique Attribute Validation
By Nick Holdren | January 19, 2012
You’ve probably seen it or experienced at some point when registering for a site where you must pick a unique username or subdomain for account registration. However, this is can be tedious to implement in both frameworks and non-framework solutions. Luckily, Yii has validation rules that can be implemented easily and can be user-defined for special cases. Therefore, I’ve created this custom validation rule that checks for uniqueness of a row value for a given column within a model.
First, we need to add the rule to the array of rules
array("company_name, email", "doesNotExist")
Next, we need to define the method doesNotExist:
public function doesNotExist($attribute, $params){
$count = self::model()->count("{$attribute}=:attribute", array(":attribute" => $this->getAttribute($attribute)));
if($count > 0){
$this->addError($attribute, "This ".strtolower($this->getAttributeLabel($attribute))." already exists please choose a different value.");
}
}
Once implemented it will display an error within the form notifying the user that the value for the field they entered is not unique within the system.



Recent Comments