我可以这样做来搜索表中的电子邮件。在查询数据库之前使用模型进行验证
// controller method
public function forgot_password() {
if ($this->Session->read('Auth.User')) {
$this->redirect(array('action' => 'add'));
} else {
if ($this->request->is('post') || $this->request->is('put')) {
$user = $this->User->findByEmail($this->request->data('User.email'));
if ($user) {
$this->request->data['User']['id'] = $user['User']['id'];
$this->request->data['User']['random_string'] = $this->String->random();
unset($this->request->data['User']['email']);
$this->User->save($this->request->data);
// $this->_sendEmail($user);
$this->Session->setFlash(__('Instructions has been sent to your email'), 'flash');
$this->redirect(array('action' => 'forgot_password'));
} else {
// passed! do stuff
}
}
}
}
// validate in the model
public $validate = array(
'email' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'An Email is required'
),
'email' => array(
'rule' => array('email'),
'message' => 'Email is invalid'
),
'isUnique' => array(
'rule' => array('isUnique'),
'message' => 'Email is already in use'
)
),
'password' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'A password is required'
)
),
'role' => array(
'valid' => array(
'rule' => array('inList', array('admin', 'author')),
'message' => 'Please enter a valid role',
'allowEmpty' => false
)
)
);
上面的代码工作正常。
我只是想在验证数据库之前验证电子邮件是否是有效的电子邮件或为空。我想出了下面的一个。我遇到的问题是使用$this->request->data
来设置用户。无论何时验证,它都通过isUnique规则运行并失败。
public function forgot_password() {
if ($this->Session->read('Auth.User')) {
$this->redirect(array('action' => 'add'));
} else {
if ($this->request->is('post') || $this->request->is('put')) {
$this->User->set($this->request->data);
if ($this->User->validates()) {
$user = $this->User->findByEmail($this->request->data('User.email'));
if ($user) {
$this->request->data['User']['id'] = $user['User']['id'];
$this->request->data['User']['random_string'] = $this->String->random();
unset($this->request->data['User']['email']);
$this->User->save($this->request->data);
// $this->_sendEmail($user);
$this->Session->setFlash(__('Instructions has been sent to your email'), 'flash');
$this->redirect(array('action' => 'forgot_password'));
}
}
}
}
}
已经有人做过类似的,以我想要什么解决办法?
倘使你写了一个简短的解释(而不仅仅是代码)你做了什么/希望做什么 – Dave
我想我已经解释了很多,我已经验证,并且由于验证规则'isUnique'而失败,我想验证模型不查询数据库 –