recently I’ve created a simple registration form and when i try to save the data, if i enter an existing username or email i get an error saying that the query is stopped becasue the field already exists
In some cases this is a great feature, and i could use it in the email case.
Im not sure if i have to set this in the form validators or in the config.php or in my module.
here is my save method:
public function saveUser(User $user)
{
$data = array(
'username' => $user->username,
'email' => $user->email,
'password' => $user->password,
);
$id = (int) $user->user_id;
if ($id == 0) {
$this->insert($data);
} elseif ($this->getUser($id)) {
$this->update(
$data,
array(
'user_id' => $user_id,
)
);
} else {
throw new \Exception('Form id does not exist');
}
}
and here is the short error:
Statement could not be executed
...
QLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'admin' for key 'username'
....
like i said, i could use this error for the email, because i want unique email, but im not sure how to catch this error and display it in a nicer format, maybe like a validation error.
any ideas on this issue?
thanks
This is error returned by your SQL server. To get rid of this you need to remove
UNIQUE KEYfrom your fieldusername.As for displaying “nice error message” if user email is duplicate, I’m afraid the only choice you have is to check its existence before executing
INSERT.I once had database model which was throwing
Database_UniqueKey_Exception( $field)which allowed you to do this in quite stylish fashion, but AFAIK Zend doesn’t support special handling for unique key issues and you have to either parse error message (I wouldn’t go there) or check it in advance.