我已经尝试调试了大约两天,并在互联网上阅读了这个问题的所有答案......但仍然无法让它工作。
在我的 CakePHP 应用程序中,我有一个用户注册表单,它使用一个名为User的模型和Form helper。当验证失败时,表单不会显示任何验证错误。
根据$this->User->validationErrors
,在呈现视图之前正确填充了数组debug()
,并且通过 检测到模型未验证的事实$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_username和password_confirm字段实际上不是数据库的一部分,但仍需要验证。
我的用户模型确实有一个$validate
变量,当它插入到正确的位置时, Form可以识别该变量。required="required"
任何帮助,将不胜感激。