我正在写一个页面,我的用户可以更改他们的帐户电子邮件和密码.这是控制器动作和视图:
# 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中输入的密码与我在数据库中的密码相匹配.我的用户模型中的一个验证规则是:
'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似乎只验证此字段.例如,如果输入错误的值并按“保存更改”,页面将刷新,但不会弹出验证错误.如果我输入另一个错误的值,我会收到验证错误.出于某种原因,我需要提交表格两次以进行验证.
任何人都可以找出原因吗?
最佳答案 $this-> request-> is(‘post’)在您第一次提交表单时为false,在您第二次提交表单时为true.查看lib / Cake / Console / Templates / default / actions / controller_actions.ctp文件,您会看到当您烘焙控制器操作时,这是用于编辑操作的代码:
if ($this->request->is('post') || $this->request->is('put')) {
如果您使用上述代码,将处理第一个表单提交(因为$this-> request->是(‘put’)将为true).
查看FormHelper类的create方法(位于lib / Cake / View / Helper / FormHelper.php中),以查看何时将表单视为PUT以及何时将其视为POST.