Table of Contents
Checking for duplicate records
If you want to validate a form field (such as a user ID field) and make sure that the selected user ID does not already exist in the database, here’s a simple way to do it:
Controller code
class UserController extends AppController { function add() { if ($this->User->isUnique($this->data['User']['username'])) { if ($this->User->save($this->data)) { $this->flash('User has been saved.','/users/index'); } } } }
Model code
class User extends AppModel { function isUnique($userName) { $userNames['User.username'] = $userName; if ($this->hasAny($userNames)) { $this->invalidate('userNameExists'); return false; } else { return true; } } }
View code
echo $html->tagErrorMsg('User/userNameExists', 'User name already exists. Please choose another.')