gpt4 book ai didi

php - CakePHP 需要两次页面加载来验证表单

转载 作者:可可西里 更新时间:2023-10-31 23:32:27 25 4
gpt4 key购买 nike

我正在编写一个页面,我的用户可以在其中更改他们的帐户电子邮件和密码。这是 Controller 操作和 View :

# 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 似乎只在加载两个页面后才验证此字段。例如,如果我输入错误的值并按“保存更改”,页面会刷新,但不会弹出验证错误。如果我输入另一个错误的值,我会收到验证错误。出于某种原因,我需要提交两次表单才能进行验证。

谁能解释这是为什么?

最佳答案

$this->request->is('post')false第一次提交表格和 true第二次提交。看lib/Cake/Console/Templates/default/actions/controller_actions.ctp文件,你会看到当你烘焙 Controller Action 时,这是用于 edit 的代码 Action :

if ($this->request->is('post') || $this->request->is('put')) {

如果您使用上面的代码,将处理第一个表单提交(因为 $this->request->is('put') 将是 true )。

查看FormHelper类(class)的create方法(位于 lib/Cake/View/Helper/FormHelper.php )来查看表单何时被视为 PUT 以及何时被视为 POST。

关于php - CakePHP 需要两次页面加载来验证表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14822154/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com