gpt4 book ai didi

php - CakePHP 2.3 表单不显示验证错误

转载 作者:太空狗 更新时间:2023-10-29 15:01:38 25 4
gpt4 key购买 nike

我已经尝试调试它大约两天了,并且已经在互联网上阅读了这个问题的所有答案......但仍然无法让它工作。

在我的 CakePHP 应用程序中,我有一个用户注册表单,它使用名为 User 的模型和 Form 助手。当验证失败时,表单不会显示任何验证错误。

根据 debug()$this->User->validationErrors 数组在渲染 View 之前被正确填充,并且模型没有验证由 $this->User->save() 检测到。

这是我的观点:

<?php
echo $this->Form->create('User');
echo $this->Form->input('soton_username', array('label' => 'Email address', 'after' => '@soton.ac.uk'));
echo $this->Form->input('username', array('label' => 'Choose a username'));
echo $this->Form->input('password');
echo $this->Form->input('password_confirm', array('label' => 'Password (again)', 'type' => 'password'));
echo $this->Form->input('first_name');
echo $this->Form->input('last_name');
echo $this->Form->submit('Create account');
echo $this->Form->end();
?>

这是我的操作:

public function create() {
if($this->request->is('post')) {
$this->User->set($this->request->data);

$valid = true;
$validationErrors = array();
$password = $this->request->data('User.password');
$password_confirm = $this->request->data('User.password_confirm');

if(strlen($password) < 5) {
$validationErrors['password'][] = 'Password must be at least 5 characters long';
$valid = false;
}

if($password != $password_confirm) {
$validationErrors['password_confirm'][] ='Passwords do not match';
$valid = false;
}

$this->User->data['User']['email'] = $this->request->data('User.soton_username') . '@soton.ac.uk';

$group = $this->Group->find('first', array('conditions' => array('default' => 1)));
if($group) {
$gid = $group['Group']['id'];
} else {
$gid = 1;
}
$this->User->data['User']['group_id'] = $gid;

if($this->User->validates() && $valid) {
$this->User->save();
$this->Session->setFlash('<a href="/users/activate/' . $this->User->data['User']['activation_id'] . '">Activate</a>');
return $this->redirect('/users/confirm_create');
}

$this->User->validationErrors = array_merge($this->User->validationErrors, $validationErrors);

if(isset($this->User->validationErrors['email'])) {
$this->User->validationErrors['soton_username'] = $this->User->validationErrors['email'];
}

//debug($this->request->validationErrors);exit;
$this->Session->setFlash('There were errors with the form.');
}
}

soton_usernamepassword_confirm> 字段实际上不是数据库的一部分,但仍需要验证。

我的 User 模型确实有一个 $validate 变量,Form 在插入 required="required" 在正确的地方。

如有任何帮助,我们将不胜感激。

最佳答案

好的,我已经找到问题的答案了。

我的 AppController 类中的以下函数是罪魁祸首:

public function beforeRender() {
$user_id = $this->Auth->user('id');
$user = $this->User->read(null, $user_id);
$this->set('user', $user);
}

出于某种原因,调用 $this->Model->read() 函数会阻止显示验证错误,并且此函数在每个操作结束时都会调用它。将其移至 beforeFilter() 函数可解决此问题。

关于php - CakePHP 2.3 表单不显示验证错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17799641/

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