是否可以在CakePHP中的控制器内获取Model错误代码?

时间:2010-03-11 02:07:25

标签: mysql cakephp

我的Unsubscribed控制器中有一个简单的取消订阅功能。

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');
}

这是问题所在。我想将数据库中的电子邮件地址设置为唯一。因此,如果有人多次输入电子邮件地址(或者我们已经在取消订阅列表中输入了该电子邮件地址),我们就不会使用重复记录填充数据库。但是,我希望访问者知道他们已被添加到数据库中(因此他们知道他们已取消订阅)。

有没有办法从控制器检测重复输入错误,所以我可以将其等同于成功?需要注意的是,我不想创建扩展的app_model。有任何想法吗?可以吗?最好的方法是如何做到的?

解决方案:这是我实施的最终解决方案。我添加了验证(如下面所选答案的建议),我更新了我的控制器,如下所示:

// 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');

3 个答案:

答案 0 :(得分:2)

使用isUnique验证规则怎么样?然后只需使用验证错误通知用户。

var $validate = array(
    'login' => array(
        'rule' => 'isUnique',
        'message' => 'This username has already been taken.'
    )
);

直接从食谱中偷走了这个。第4.1.4.14 isUnique节准确无误。

答案 1 :(得分:1)

我认为你可以这样做:

if ($this->Unsubscribe->find('count',array('conditions'=>array('email'=>$this->data['Unsubscribes']['email']))) > 0   )
{
   $this->Session->setFlash('duplicate email!');
   $this->redirect('/unsubscribes/unsubscribe');
}
//then do your stuff 

答案 2 :(得分:0)

这取决于。是否还有其他可能出现的错误要显示?或者这是唯一可能发生的错误?如果是后者,请不要检查:

$this->Unsubscribe->save($this->data['Unsubscribes']);
// I don't care if that actually saved or not,
// unless something horrible happened the email is in the database
$this->Session->setFlash('Your email has been unsubscribed!');
$this->redirect('/unsubscribes/unsubscribe');

否则,您可以使用invalidFields()方法找出问题所在。