CakePHP需要两个页面加载来验证表单

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了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中输入的密码与我在数据库中的密码相匹配.我的用户模型中的一个@R_777_1851@是:

'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.

脚本宝典总结

以上是脚本宝典为你收集整理的CakePHP需要两个页面加载来验证表单全部内容,希望文章能够帮你解决CakePHP需要两个页面加载来验证表单所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。