0
votes

I'm trying to display error messages together for every wrong input in form.

For example: User must set his name, age and email, but he set only name. Validator returns correctly false on notEmpty rule for age field. but it always return one error, but I need to get two errors - first error for empty age field and second for empty email field.

After user added his age and submit data, (mail field had still empty) validator return error on notEmpty rule for email. But i need this error together with age error in previous submit.

How to group error messages together?

1

1 Answers

4
votes

Have you set all the validation rule in Model/Table/UsersTable.php?

It should look something like this.

   <?php
   //Model/Table/UsersTable.php
   namespace App\Model\Table;
   use Cake\ORM\Table;
   use Cake\Validation\Validator;

   class UsersTable extends Table{

        public function validationDefault(Validator $validator){

        $validator  =   new Validator();

        $validator
            ->notEmpty("username","Name cannot be empty.")
            ->requirePresence("name")
            ->notEmpty("username","Email cannot be empty.")
            ->requirePresence("email")
            ->notEmpty("username","Age cannot be empty.")
            ->requirePresence("age");
    }
  ?>

Now, in your controller, you need to write the following:

   //UsersController.php


   public function add(){

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

        if($this->request->is("post")){
            $user   =   $this->Users->patchEntity($user, $this->request->data);
            if($this->Users->save($user)){
                $this->Flash->success(__('User has been saved.'));
                return $this->redirect(['controller' => 'users', 'action' => 'login']);
            }

            if($user->errors()){
                $error_msg = [];
                foreach( $user->errors() as $errors){
                    if(is_array($errors)){
                        foreach($errors as $error){
                            $error_msg[]    =   $error;
                        }
                    }else{
                        $error_msg[]    =   $errors;
                    }
                }

                if(!empty($error_msg)){
                    $this->Flash->error(
                        __("Please fix the following error(s):".implode("\n \r", $error_msg))
                    );
                }
            }

        }

        $this->set(compact("user"));

    }

Hope this solves your problem.

Peace! xD