微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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','autocomplete' => 'off')); ?>
<?PHP echo $this->Form->input('confirmPassword','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.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐