CakePHP 3- Showing all error and buildRules messages in controller

泪湿孤枕 提交于 2019-12-06 12:47:32

问题


I have this Model/Table/UsersProfilesTable.php where I have specified all the error messages and buildRules.

My intention is to list all the validation errors in the controller while attempting to save the data.

The code is mentioned below.

 // Model/Table/UsersProfilesTable.php 

 class UserProfilesTable extends Table{

    public function validationDefault(Validator $validator){

        $validator  =   new Validator();

        $validator
            ->notEmpty("first_name","First name cannot be empty.")
            ->requirePresence("first_name")
            .......
            ->notEmpty("email", "Email cannot be empty.")
            ->requirePresence("email")
            ->add( "email", "email",[
                "rule" => ["email", true],
                "message" => "Enter a valid e-mail."
            ]);



        return $validator;  
    }

    public function buildRules(RulesChecker $rules){

        $rules->add($rules->isUnique(['email'], 'Email should be unique'));

        return $rules;
    }

    //UsersController.php

      $user =   $this->Users->patchEntity($user, $this->request->data);

      if($this->Users->save($user)){
        // Success msg
      }

      if($user->errors()){
         // This shows all the error messages except the one specified in the  buildRules for unique email.
         pr($user->errors()); 
      }

Can anyone please come up with a way in which I can list all the validation errors including the message specified in the buildRules method?

Any help would be appreciated. Thanks in advance!

Peace! xD


回答1:


Remember that validation is a 2 phase process, first all the validatiton rules are checked (during marshalling - i.e. patchEntity()), only if they pass are the rules in buildRules are used. This means that the unique email rule will not be run until the standard validation rules all pass.

If you need immediate feedback for email uniqueness you can also add a validation rule for email uniqueness in the validator.




回答2:


You can use this to force Cake to check the rules even if validation fails:

$this->Users->checkRules($user);


来源:https://stackoverflow.com/questions/35251285/cakephp-3-showing-all-error-and-buildrules-messages-in-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!