I was talking to Matthew Pennell about his new RoR hobby and he was saying that one little bit he appreciated was how easy rails makes it to validate_uniqueness.
I tried to add a unique method to the cake validation core, but the level of separation between the Model & the validation classes was beyond me.
So….here is the code for your model:
var $validate = array(
'email' =>array('rule' =>array('_isUnique', 'email'))
);
Where every instance of “email” in the above code should be replaced with the fieldname that you wish to validate as unique.
Then put the following code in your AppModel class (app_model.php in your app folder.) If app_model.php does not exist in your application, copy the one found at cake/console/libs/templates/skel into your own app directory.
/** * Checks that a value is unique * * @param string $check Value to check * @param string $field Field to check for value * @return boolean Success * @access public */ function _isUnique($check, $field) { $conditions = array(); foreach($check as $c) { $conditions[] = "$this->name.$field=\"" . addslashes($c) . "\""; }if(isset($this->data[$this->name][id])){ $conditions[] = "$this->name.id\"".addslashes($this->data[$this->name]['id'])."\""; }$results = $this->find($conditions);if(!empty($results)) { return false; } else { return true; } }
(Fixed thanks to Ambiguator’s comment)
You should not need to change this function. I am grabbing anything that is specific to your model, from your application (and class instance).