I have a simple unsubscribe function in my Unsubscribed controller.
if ($this->Unsubscribe->save($this->data['Unsubscribes'])) {
// success
$this->Session->setFlash('Your email has been unsubscribed!');
$this->redirect('/unsubscribes/unsubscribe');
} else {
// error
$this->Session->setFlash('There was an error!');
$this->redirect('/unsubscribes/unsubscribe');
}
Here is the problem. I want to set the email address in the database as unique. So if someone enters the email address multiple times (or we already have it in our unsubscribe list), we are not populating the database with duplicate records. However, I want the visitor to know they have been added to the database (so they know they are unsubscribed).
Is there a way to detect the Duplicate entry error from the controller so I can equate that to a success? The caveat, I don't want to create a extended app_model. Any ideas? Can it be done? How is the best way to do this?
SOLUTION: Here is the final solution I implemented. I added the validation (as suggested by the chosen answer below) and I updated my controller as follows:
// error
if(isset($this->Unsubscribe->validationErrors['email'])){
$error = 'Your email has been unsubscribed!';
} else {
$error = 'Something went wrong. Please try again.';
}
$this->Session->setFlash($error);
$this->redirect('/unsubscribes/unsubscribe');