我一直在試圖調試這個問題大約兩天,並且已經閱讀了互聯網上對這個問題的每一個答案......並且仍然無法讓它工作。CakePHP 2.3表單不顯示驗證錯誤
在我的CakePHP應用程序我有一個用戶登錄表單,它使用了一個名爲用戶和形式幫手模型。當驗證失敗時,表單不顯示任何驗證錯誤。
根據debug()
,在呈現視圖之前$this->User->validationErrors
陣列已正確填充,並且模型未驗證的事實由$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="https://stackoverflow.com/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
變量,形式不承認它插入在正確的地方required="required"
。
任何幫助,將不勝感激。
謝謝,這解決了我的問題。順便說一句,你可以在視圖中使用AuthComponent :: user(),所以在beforeFilter()中不需要該代碼() – Will
8個月後解決了我的問題。謝謝! – harmjanr