我在寫一個頁面,我的用戶可以更改他們的帳戶電子郵件和密碼。這裏是控制器的動作和視圖:CakePHP需要兩個頁面加載來驗證表單
# UsersController.php
public function edit() {
if($this->request->is('post')) {
if($this->User->save($this->request->data)) {
$this->Session->setFlash('Your account has been updated.');
$this->redirect(array('action' => 'edit'));
}
$this->Session->setFlash('There was a problem saving your account settings. Please try again.');
}
// Auto populate form fields
if(!$this->request->data) {
$this->request->data = $this->User->find('first', array(
'conditions' => array('User.id' => $this->Auth->user('id'))
));
}
}
# edit.ctp
<?php echo $this->Form->create('User'); ?>
<?php echo $this->Form->input('currentPassword', array('between' => 'You must enter your password in order to make changes', 'type' => 'password', 'value' => '', 'autocomplete' => 'off')); ?>
<?php echo $this->Form->input('email'); ?>
<?php echo $this->Form->input('password', array('type' => 'password', 'between' => 'Must be atleast 6 characters', 'value' => '', 'autocomplete' => 'off')); ?>
<?php echo $this->Form->input('confirmPassword', array('type' => 'password', 'value' => '', 'autocomplete' => 'off')); ?>
<?php echo $this->Form->end('Save changes'); ?>
現在,我想讓用戶輸入他們的當前密碼以進行更改。爲了達到這個目的,我需要運行驗證檢查以確保他們在currentPassword
中輸入的密碼與我在數據庫中的密碼匹配。一個在我User
模型的驗證規則是這樣的:
'currentPassword' => array(
'custom' => array(
'rule' => 'validateCurrentPassword',
'message' => 'Incorrect password. Make sure you\'re using your current password.'
)
),
和相關函數被調用:
public function validateCurrentPassword($data) {
debug($data);
return false;
}
到目前爲止好,但有一些很怪異的行爲。 Cake似乎只在兩次頁面加載後驗證此字段。例如,如果我輸入了錯誤的值並按下「保存更改」頁面刷新,但沒有驗證錯誤彈出。如果我輸入另一個錯誤的值,則會出現驗證錯誤。出於某種原因,我需要提交表單兩次以進行驗證。
任何人都可以解決這是爲什麼?
這很奇怪。那麼,它是否在第一次提交表單時顯示「存在問題......」?您第一次保存時,是否在控制器中設置了變量validationErrors? DebugKit可能有助於調試。另外,你有沒有像beforeSave,afterSave等模型中的回調或控制器中的beforeFilter回調? – jimiyash 2013-02-12 03:41:14