Sharon
Sharon

Reputation: 3909

CakePHP 4.0 - how do I create and show validation errors against fields?

I'm using CakePHP 4.0, and creating a user registration page. I've set up some validation rules, which are returning errors when expected, but I can't figure out how to get them to show against the appropriate fields in the form. In v3.0 this seemed to happen automatically.

My form (in register.php) is:

echo $this->Flash->render();
echo $this->Form->create();
echo $this->Form->control('name');
echo $this->Form->control('email');
echo $this->Form->control('password', array('type' => 'password'));
echo $this->Form->control('confirm_password', array('type' => 'password'));

In UsersController.php I have the action register:

    public function register() {

        $user = $this->Users->newEmptyEntity();

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

            $user = $this->Users->patchEntity($user, $this->request->getData());
            if($user->getErrors()) {
                $this->Flash->error(__('Unable to register you.  Please make sure you have completed all fields correctly.'));
            }else {
                $this->Users->save($user);
                $this->Flash->success(__('Success'));
                return redirect($this->get_home());
           }

       }

       $this->set('user', $user);

   }

The validation rule in UsersTable is:

public function validationDefault(Validator $validator): Validator {

    $validator->requirePresence([
                'name' => [
                        'mode' => 'create',
                        'message' => 'Please enter your name'
                ],
                'email' => [
                        'mode' => true,
                        'message' => 'Please enter your email address'
                ]
            ])
            ->allowEmptyString('name', 'Name cannot be empty', false);
}

If I submit the form without entering anything for the name or email address, getErrors() picks up the invalid fields and creates an array, which I can see via debug contains:

'name' => [
        '_empty' => 'Name cannot be empty'
    ]

So it has realised that name field doesn't validate, but it doesn't show it against the field in the form (or anywhere) as it did in version 3.0.

What else do I need to do?

Upvotes: 1

Views: 2914

Answers (1)

Sharon
Sharon

Reputation: 3909

Thanks to Salines, I used

echo $this->Form->create($user);

instead of

echo $this->Form->create();

and errors immediately showed up.

Upvotes: 1

Related Questions