我可以這樣做來搜索表中的電子郵件。在查詢數據庫之前使用模型進行驗證
// 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'而失敗,我想驗證模型不查詢數據庫 –