【问题标题】:CakePHP 3- Showing all error and buildRules messages in controllerCakePHP 3- 在控制器中显示所有错误和 buildRules 消息
【发布时间】:2016-05-17 00:46:01
【问题描述】:

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

我的目的是在尝试保存数据时列出控制器中的所有验证错误。

代码如下。

 // 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 方法中指定的消息?

任何帮助将不胜感激。提前致谢!

和平! xD

【问题讨论】:

    标签: cakephp cakephp-3.0 cakephp-3.x


    【解决方案1】:

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

    如果您需要电子邮件唯一性的即时反馈,您还可以在验证器中添加电子邮件唯一性验证规则。

    【讨论】:

      【解决方案2】:

      即使验证失败,您也可以使用它来强制 Cake 检查规则:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-09-02
        • 2019-03-24
        • 2020-12-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多