CakePHP 3-在控制器中显示所有错误和buildRules消息 [英] CakePHP 3- Showing all error and buildRules messages in controller

查看:84
本文介绍了CakePHP 3-在控制器中显示所有错误和buildRules消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个Model / Table / UsersProfilesTable.php文件,其中指定了所有错误消息和buildRules。

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.

代码在下面提到。

 // 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()); 
      }

有人可以提出一种列出所有验证的方法吗?错误包括在buildRules方法中指定的消息?

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!

和平! xD

推荐答案

请记住,验证是一个两阶段过程,首先检查所有验证规则(在编组期间-即 patchEntity()),仅在通过buildRules中的规则的情况下使用。这意味着唯一的电子邮件规则将在标准验证规则全部通过之前运行。

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.

这篇关于CakePHP 3-在控制器中显示所有错误和buildRules消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆