I tried to debug this for about two days and read every answer to this question on the Internet ... and still cannot get it to work.
In my CakePHP application, I have a user registration form that uses the User model and form assistant. When validation fails, the form does not display validation errors.
The $this->User->validationErrors array is correctly populated before the view is rendered according to debug() , and the fact that the model is not validated is determined by $this->User->save() .
Here is my view:
<?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(); ?>
Here is my action:
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']; }
The soton_username and password_confirm fields are not really part of the database, but they still need to be checked.
There is a $validate variable in my user model that the form recognizes when it inserts required="required" in the right places.
Any help would be appreciated.
source share