【问题标题】:Symfony2 : How to get form validation errors after binding the request to the formSymfony2:将请求绑定到表单后如何获取表单验证错误
【发布时间】:2011-10-22 03:58:15
【问题描述】:

这是我的saveAction 代码(表单将数据传递到的地方)

public function saveAction()
{
    $user = OBUser();

    $form = $this->createForm(new OBUserType(), $user);

    if ($this->request->getMethod() == 'POST')
    {
        $form->bindRequest($this->request);
        if ($form->isValid())
            return $this->redirect($this->generateUrl('success_page'));
        else
            return $this->redirect($this->generateUrl('registration_form'));
    } else
        return new Response();
}

我的问题是:如果$form->isValid() 返回false,我如何得到错误?

【问题讨论】:

    标签: symfony


    【解决方案1】:

    你有两种可能的方法:

    • 出错时不重定向用户并在模板文件中显示{{ form_errors(form) }}
    • 以$form->getErrors() 访问错误数组

    【讨论】:

    • 我做了你建议的第二件事,但是 form->getErrors() 返回一个空白数组。
    • 我也做了第一个(带有 php 模板 errors($form) ?>)但它仍然是空的!
    • @mives 您必须在表单类型中将error_bubbling 设置为true,方法是为每个字段显式设置选项。
    • 如果您使用自定义验证器,Symfony 不会返回由 $form->getErrors() 中的验证器生成的错误。
    • 您也可以使用$form->getErrors(true) 来包含子表单的错误
    【解决方案2】:

    Symfony 2.3 / 2.4:

    这个函数得到所有的错误。表单上的类似“CSRF 令牌无效。请尝试重新提交表单”。以及没有错误冒泡的表单子项上的其他错误。

    private function getErrorMessages(\Symfony\Component\Form\Form $form) {
        $errors = array();
    
        foreach ($form->getErrors() as $key => $error) {
            if ($form->isRoot()) {
                $errors['#'][] = $error->getMessage();
            } else {
                $errors[] = $error->getMessage();
            }
        }
    
        foreach ($form->all() as $child) {
            if (!$child->isValid()) {
                $errors[$child->getName()] = $this->getErrorMessages($child);
            }
        }
    
        return $errors;
    }
    

    以字符串形式获取所有错误:

    $string = var_export($this->getErrorMessages($form), true);
    

    Symfony 2.5 / 3.0:

    $string = (string) $form->getErrors(true, false);
    

    文档:
    https://github.com/symfony/symfony/blob/master/UPGRADE-2.5.md#form https://github.com/symfony/symfony/blob/master/UPGRADE-3.0.md#form(底部:The method Form::getErrorsAsString() was removed)

    【讨论】:

    • 这看起来是当前 Symfony 2.4 的最正确答案。
    • @Flip 它在 2.5 上完美运行
    • 很好的答案,但 $errors[$child->getName()] = $this->getErrorMessages($child); 抛出异常,因为 Symfony\Bundle\FrameworkBundle\Controller\Controller 组件中缺少 getErrorMessages。所以我把它换成了$form_errors[$child->getName()] = $child->getErrorsAsString();
    • @AhadAli 它是一个递归函数,因此当您将代码 sn-p 放入需要此功能的类中时,它将能够调用自身。您的“修复”将阻止您访问嵌套表单。它适用于其他 37 个人,它也应该适用于你 ;)
    • @Flip 对不起,我的错,我只看$this->getErrorMessages(),我认为它直接在控制器内部调用,也是 Symfony api 的一部分。
    【解决方案3】:

    以下是对我有用的解决方案。该函数位于控制器中,将返回一个包含所有错误消息和导致错误消息的字段的结构化数组。

    Symfony 2.0:

    private function getErrorMessages(\Symfony\Component\Form\Form $form) {
        $errors = array();
        foreach ($form->getErrors() as $key => $error) {
            $template = $error->getMessageTemplate();
            $parameters = $error->getMessageParameters();
    
            foreach($parameters as $var => $value){
                $template = str_replace($var, $value, $template);
            }
    
            $errors[$key] = $template;
        }
        if ($form->hasChildren()) {
            foreach ($form->getChildren() as $child) {
                if (!$child->isValid()) {
                    $errors[$child->getName()] = $this->getErrorMessages($child);
                }
            }
        }
    
        return $errors;
    }
    

    Symfony 2.1 和更新版本:

    private function getErrorMessages(\Symfony\Component\Form\Form $form) {      
        $errors = array();
    
        if ($form->hasChildren()) {
            foreach ($form->getChildren() as $child) {
                if (!$child->isValid()) {
                    $errors[$child->getName()] = $this->getErrorMessages($child);
                }
            }
        } else {
            foreach ($form->getErrors() as $key => $error) {
                $errors[] = $error->getMessage();
            }   
        }
    
        return $errors;
    }
    

    【讨论】:

    • 改进了gist.github.com/2011671,但仍然不是我想要的。我希望数组键是字段名称,但它们不是。
    • @SalmanPK Twig 在上面的代码中没有被引用。我不相信我理解你的评论。
    • 这是对先前要点的修复,这在 Symfony 2.1.7 下有效。 gist.github.com/WishCow/5101428
    • 在 Symfony2.1 的示例中,$this->getFormErrors 看起来应该是 $this->getErrorMessages 的错字
    • @umpirsky 要获取字段名称,我得到了这个:$child->getConfig()->getOptions()['label'] 花了我很长时间才找到...
    【解决方案4】:

    使用验证器获取特定实体的错误

    if( $form->isValid() )
    {
        // ...
    }
    else
    {
        // get a ConstraintViolationList
        $errors = $this->get('validator')->validate( $user );
    
        $result = '';
    
        // iterate on it
        foreach( $errors as $error )
        {
            // Do stuff with:
            //   $error->getPropertyPath() : the field that caused the error
            //   $error->getMessage() : the error message
        }
    }
    

    API 参考:

    【讨论】:

    • 我不确定单独验证每个实体是否是一种好方法。如果你有复杂的层次结构怎么办?第二个问题是验证发生了两次。
    • @SlavaFominII - “第二个问题是验证发生了两次” - 好点,什么都没有刷新!之后相同的错误列表!
    【解决方案5】:

    为了获得正确的(可翻译的)消息,目前使用 SF 2.6.3,这是我的最终功能(因为以上似乎都不再起作用):

     private function getErrorMessages(\Symfony\Component\Form\Form $form) {      
        $errors = array();
        foreach ($form->getErrors(true, false) as $error) {
            // My personnal need was to get translatable messages
            // $errors[] = $this->trans($error->current()->getMessage());
            $errors[] = $error->current()->getMessage();
        }
    
        return $errors;
    }
    

    因为 Form::getErrors() 方法现在返回 FormErrorIterator 的实例,除非您将第二个参数 ($flatten) 切换为 true。 (然后它将返回一个 FormError 实例,您必须直接调用 getMessage() 方法,而不使用 current() 方法:

     private function getErrorMessages(\Symfony\Component\Form\Form $form) {      
        $errors = array();
        foreach ($form->getErrors(true, true) as $error) {
            // My personnal need was to get translatable messages
            // $errors[] = $this->trans($error->getMessage());
            $errors[] = $error->getMessage();
        }
    
        return $errors;
    }
    

    )

    最重要的是实际上将第一个参数设置为 true 以获取错误。 将第二个参数 ($flatten) 保留为默认值 (true) 将返回 FormError 实例,而在设置为时返回 FormErrorIterator 实例假的。

    【讨论】:

    • 不错,使用相同的东西。
    • 不是吗? :) @KidBinary
    • 绝对漂亮,伙计:)
    • 更好的选择是:$errors = array_map(function ($item) { return $item->current()->getMessage(); }, $campaignForm->getErrors(true, false)) ;
    • Symfony 2.7 的好解决方案
    【解决方案6】:

    对于我的即时消息,我对$form->getErrorsAsString()很满意

    编辑(来自 Benji_X80): 对于 SF3,请使用 $form->getErrors(true, false);

    【讨论】:

    • 我知道这是一个旧答案,但供将来参考:This method should only be used to help debug a form. (source)
    • getErrorsAsString() 在 3.0 中已弃用,使用:$form->getErrors(true, false);
    【解决方案7】:

    symfony 2.1 和更新版本的函数,没有任何弃用的函数:

    /**
     * @param \Symfony\Component\Form\Form $form
     *
     * @return array
     */
    private function getErrorMessages(\Symfony\Component\Form\Form $form)
    {
        $errors = array();
    
        if ($form->count() > 0) {
            foreach ($form->all() as $child) {
                /**
                 * @var \Symfony\Component\Form\Form $child
                 */
                if (!$child->isValid()) {
                    $errors[$child->getName()] = $this->getErrorMessages($child);
                }
            }
        } else {
            /**
             * @var \Symfony\Component\Form\FormError $error
             */
            foreach ($form->getErrors() as $key => $error) {
                $errors[] = $error->getMessage();
            }
        }
    
        return $errors;
    }
    

    【讨论】:

    • 我打算为这篇文章发布一个新答案,但你似乎已经打败了我。我不得不查看源代码以找出找不到方法调用的原因。
    • 我注意到这不会从错误冒泡设置为 true 的项目中提取错误。 SF2.4
    • @stwe 第一个IF 语句的目的是什么?为什么是互斥的?据我所知:表单可以有它自己的错误以及孩子。
    【解决方案8】:

    翻译后的表单错误信息 (Symfony2.1)

    我一直在努力寻找这些信息,所以我认为绝对值得添加有关表单错误翻译的注释。

    @Icode4food answer 将返回表单的所有错误。但是,返回的数组不考虑消息复数或翻译。

    你可以修改@Icode4food答案的foreach循环来拥有一个combo:

    • 获取特定表单的所有错误
    • 返回翻译错误
    • 必要时考虑复数

    这里是:

    foreach ($form->getErrors() as $key => $error) {
    
       //If the message requires pluralization
        if($error->getMessagePluralization() !== null) {
            $errors[] = $this->container->get('translator')->transChoice(
                $error->getMessage(), 
                $error->getMessagePluralization(), 
                $error->getMessageParameters(), 
                'validators'
                );
        } 
        //Otherwise, we do a classic translation
        else {
            $errors[] = $this->container->get('translator')->trans(
                $error->getMessage(), 
                array(), 
                'validators'
                );
        }
    }
    

    这个答案来自 3 个不同的帖子:

    【讨论】:

    • 刚试了你的版本,它去了Fatal Error: Call to undefined method Symfony\Component\Form\FormError::getMessagePluralization()。我怀疑这仅适用于 Symfony 2.1?
    【解决方案9】:

    SYMFONY 3.X

    此处给出的其他 SF 3.X 方法对我不起作用,因为我可以向表单提交空数据(但我有 NotNull/NotBlanck 约束)。在这种情况下,错误字符串如下所示:

    string(282) "ERROR: This value should not be blank.
    ERROR: This value should not be blank.
    ERROR: This value should not be blank.
    ERROR: This value should not be blank.
    ERROR: This value should not be blank.
    ERROR: This value should not be null.
    name:
        ERROR: This value should not be blank.
    "
    

    这不是很有用。所以我做了这个:

    public function buildErrorArray(FormInterface $form)
    {
        $errors = [];
    
        foreach ($form->all() as $child) {
            $errors = array_merge(
                $errors,
                $this->buildErrorArray($child)
            );
        }
    
        foreach ($form->getErrors() as $error) {
            $errors[$error->getCause()->getPropertyPath()] = $error->getMessage();
        }
    
        return $errors;
    }
    

    哪个会返回:

    array(7) {
      ["data.name"]=>
      string(31) "This value should not be blank."
      ["data.street"]=>
      string(31) "This value should not be blank."
      ["data.zipCode"]=>
      string(31) "This value should not be blank."
      ["data.city"]=>
      string(31) "This value should not be blank."
      ["data.state"]=>
      string(31) "This value should not be blank."
      ["data.countryCode"]=>
      string(31) "This value should not be blank."
      ["data.organization"]=>
      string(30) "This value should not be null."
    }
    

    【讨论】:

      【解决方案10】:

      对于 Symfony 3.2 及更高版本使用此,

      public function buildErrorArray(FormInterface $form)
      {
          $errors = array();
      
          foreach ($form->getErrors() as $key => $error) {
              if ($form->isRoot()) {
                  $errors['#'][] = $error->getMessage();
              } else {
                  $errors[] = $error->getMessage();
              }
          }
      
          foreach ($form->all() as $child) {
              if (!$child->isValid()) {
                  $errors[$child->getName()] = (string) $child->getErrors(true, false);
              }
          }
          return $errors;
      }
      

      如果您想摆脱每个错误描述文本中烦人的“Error:”文本,请使用 str_replace。

      $errors[$child->getName()] = str_replace('ERROR:', '', (string) $child->getErrors(true, false));
      

      【讨论】:

        【解决方案11】:

        您还可以使用验证器服务来获取约束违规:

        $errors = $this->get('validator')->validate($user);
        

        【讨论】:

        • 这将验证对象而不是表单。例如,如果 CRSF 令牌是导致错误的原因,则不会包含该消息。
        【解决方案12】:

        如果您使用自定义验证器,Symfony 不会返回由 $form->getErrors() 中的验证器生成的错误。 $form->getErrorsAsString() 将返回您需要的所有错误,但遗憾的是其输出格式为字符串,而不是数组。

        你用来获取所有错误的方法(不管它们来自哪里),取决于你使用的 Symfony 版本。

        大多数建议的解决方案都涉及创建一个递归函数来扫描所有子表单,并将相关错误提取到一个数组中。 Symfony 2.3 没有$form->hasChildren() 函数,但它有$form->all()。

        这里是 Symfony 2.3 的帮助类,您可以使用它从任何形式中提取所有错误。 (它基于 yapro 对 Symfony 的 github 帐户中相关 bug 票证的评论中的代码。)

        namespace MyApp\FormBundle\Helpers;
        
        use Symfony\Component\Form\Form;
        
        class FormErrorHelper
        {
            /**
             * Work-around for bug where Symfony (2.3) does not return errors from custom validaters,
             * when you call $form->getErrors().
             * Based on code submitted in a comment here by yapro:
             * https://github.com/symfony/symfony/issues/7205
             *
             * @param Form $form
             * @return array Associative array of all errors
             */
            public function getFormErrors($form)
            {
                $errors = array();
        
                if ($form instanceof Form) {
                    foreach ($form->getErrors() as $error) {
                        $errors[] = $error->getMessage();
                    }
        
                    foreach ($form->all() as $key => $child) {
                        /** @var $child Form */
                        if ($err = $this->getFormErrors($child)) {
                            $errors[$key] = $err;
                        }
                    }
                }
        
                return $errors;
            }
        }
        

        调用代码:

        namespace MyApp\ABCBundle\Controller;
        
        use MyApp\FormBundle\Helpers;
        
        class MyController extends Controller
        {
            public function XYZAction()
            {
                // Create form.
        
                if (!$form->isValid()) {
                    $formErrorHelper = new FormErrorHelper();
                    $formErrors = $formErrorHelper->getFormErrors($form);
        
                    // Set error array into twig template here.
                }
            }
        
        }
        

        【讨论】:

          【解决方案13】:

          翻译后的表单错误信息 (Symfony2.3)

          我解决问题的版本:

          /src/Acme/MyBundle/Resources/config/services.yml

          services:
              form_errors:
                  class: Acme\MyBundle\Form\FormErrors
          

          /src/Acme/MyBundle/Form/FormErrors.php

          <?php
          namespace Acme\MyBundle\Form;
          
          class FormErrors
          {
              public function getArray(\Symfony\Component\Form\Form $form)
              {
                  return $this->getErrors($form);
              }
          
              private function getErrors($form)
              {
                  $errors = array();
          
                  if ($form instanceof \Symfony\Component\Form\Form) {
          
                      // соберем ошибки элемента
                      foreach ($form->getErrors() as $error) {
          
                          $errors[] = $error->getMessage();
                      }
          
                      // пробежимся под дочерним элементам
                      foreach ($form->all() as $key => $child) {
                          /** @var $child \Symfony\Component\Form\Form */
                          if ($err = $this->getErrors($child)) {
                              $errors[$key] = $err;
                          }
                      }
                  }
          
                  return $errors;
              }
          }
          

          /src/Acme/MyBundle/Controller/DefaultController.php

          $form = $this->createFormBuilder($entity)->getForm();
          $form_errors = $this->get('form_errors')->getArray($form);
          return new JsonResponse($form_errors);
          

          在 Symfony 2.5 中,您可以很容易地得到所有字段错误:

              $errors = array();
              foreach ($form as $fieldName => $formField) {
                  foreach ($formField->getErrors(true) as $error) {
                      $errors[$fieldName] = $error->getMessage();
                  }
              }
          

          【讨论】:

            【解决方案14】:

            根据@Jay Seth 的回答,我特别为 Ajax 表单制作了一个 FormErrors 类版本:

            // src/AppBundle/Form/FormErrors.php
            namespace AppBundle\Form;
            
            class FormErrors
            {
            
                /**
                 * @param \Symfony\Component\Form\Form $form
                 *
                 * @return array $errors
                 */
                public function getArray(\Symfony\Component\Form\Form $form)
                {
                    return $this->getErrors($form, $form->getName());
                }
            
                /**
                 * @param \Symfony\Component\Form\Form $baseForm
                 * @param \Symfony\Component\Form\Form $baseFormName
                 *
                 * @return array $errors
                 */
                private function getErrors($baseForm, $baseFormName) {
                    $errors = array();
                    if ($baseForm instanceof \Symfony\Component\Form\Form) {
                        foreach($baseForm->getErrors() as $error) {
                            $errors[] = array(
                                "mess"      => $error->getMessage(),
                                "key"       => $baseFormName
                            );
                        }
            
                        foreach ($baseForm->all() as $key => $child) {
                            if(($child instanceof \Symfony\Component\Form\Form)) {
                                $cErrors = $this->getErrors($child, $baseFormName . "_" . $child->getName());
                                $errors = array_merge($errors, $cErrors);
                            }
                        }
                    }
                    return $errors;
                }
            }
            

            用法(例如在你的行动中):

            $errors = $this->get('form_errors')->getArray($form);
            

            Symfony 版本:2.8.4

            示例 JSON 响应:

            {
                "success": false,
                "errors": [{
                    "mess": "error_message",
                    "key": "RegistrationForm_user_firstname"
                }, {
                    "mess": "error_message",
                    "key": "RegistrationForm_user_lastname"
                }, {
                    "mess": "error_message",
                    "key": "RegistrationForm_user_email"
                }, {
                    "mess": "error_message",
                    "key": "RegistrationForm_user_zipCode"
                }, {
                    "mess": "error_message",
                    "key": "RegistrationForm_user_password_password"
                }, {
                    "mess": "error_message",
                    "key": "RegistrationForm_terms"
                }, {
                    "mess": "error_message2",
                    "key": "RegistrationForm_terms"
                }, {
                    "mess": "error_message",
                    "key": "RegistrationForm_marketing"
                }, {
                    "mess": "error_message2",
                    "key": "RegistrationForm_marketing"
                }]
            }
            

            错误对象包含“key”字段,即输入 DOM 元素的 id,因此您可以轻松填充错误消息。

            如果您在父表单中有子表单,请不要忘记在父表单的 setDefaults 中添加 cascade_validation 选项。

            【讨论】:

              【解决方案15】:

              Symfony 3 和更新版本

              我最近制作了一个创建表单错误树的函数。这将有助于将错误列表返回到前端。这基于具有以下特征的表单类型:

              'error_bubbling' => false
              

              代码:

              public static function getFormErrorsTree(FormInterface $form): array
              {
                  $errors = [];
              
                  if (count($form->getErrors()) > 0) {
                      foreach ($form->getErrors() as $error) {
                          $errors[] = $error->getMessage();
                      }
                  } else {
                      foreach ($form->all() as $child) {
                          $childTree = self::getFormErrorsTree($child);
              
                          if (count($childTree) > 0) {
                              $errors[$child->getName()] = $childTree;
                          }
                      }
                  }
              
                  return $errors;
              }
              

              输出:

              Array
              (
                  [name] => Array
                      (
                          [0] => This value is not valid.
                      )
              
                  [emails] => Array
                      (
                          [0] => Array
                              (
                                  [0] => Given e-mail is not valid.
                                  [1] => Given e-mail is not valid #2.
                              )
                          [1] => Array
                              (
                                  [0] => Given e-mail is not valid.
                                  [1] => Given e-mail is not valid #2.
                              )
              
                      )
              
              )
              
              

              注意:我知道如果更高级别有错误,来自更深级别字段的错误可以被覆盖,但这是我故意使用的。

              【讨论】:

                【解决方案16】:

                对于 Symfony 5 我得到了这个工作:

                public function getErrorMessages(Form $form) {
                  
                    $errors = [];        
                
                    foreach ($form->all() as $child) {
                        foreach ($child->getErrors() as $error) {
                                $name = $child->getName();
                                $errors[$name] = $error->getMessage();
                        }
                    }
                
                    return $errors;
                }
                

                我得到了这种 JSON 的东西:

                errors: {
                    firstname: "The firstname must be between 2 and 30 characters long.",
                    lastname: "The lastname must be between 2 and 40 characters long."
                    subject: "Please choose a subject."
                    text: "Empty messages are not allowed."
                }
                

                它对我来说已经足够好用了,但我想它不会在全局级别发现错误,比如超时令牌或其他类似的东西。 无论如何,我一直在寻找适合我的情况的解决方案,我很高兴在这里做出贡献,希望它能够以某种方式在某个地方帮助一些开发人员。

                【讨论】:

                  【解决方案17】:

                  对于 Symfony 2.1 及更高版本以用于 Twig 错误显示,我更改了函数以添加 FormError 而不是简单地检索它们,这样您可以更好地控制错误并且不必在每个单独的输入上使用 error_bubbling。如果不按以下方式设置 {{ form_errors(form) }} 将保持空白:

                  /**
                   * @param \Symfony\Component\Form\Form $form
                   *
                   * @return void
                   */
                  private function setErrorMessages(\Symfony\Component\Form\Form $form) {      
                  
                      if ($form->count() > 0) {
                          foreach ($form->all() as $child) {
                              if (!$child->isValid()) {
                                  if( isset($this->getErrorMessages($child)[0]) ) {
                                      $error = new FormError( $this->getErrorMessages($child)[0] );
                                      $form->addError($error);
                                  }
                              }
                          }
                      }
                  
                  }
                  

                  【讨论】:

                    【解决方案18】:

                    $form->getErrors() 对我有用。

                    【讨论】:

                      【解决方案19】:

                      我想出了这个解决方案。它可以与最新的 Symfony 2.4 配合使用。

                      我会尽量给出一些解释。

                      使用单独的验证器

                      我认为使用单独的验证来验证实体并返回违反约束的消息是一个坏主意,就像其他作者所建议的那样。

                      1. 您将需要手动验证所有实体,指定验证组等。对于复杂的分层表单,它根本不实用,并且很快就会失控。

                      2. 这样您将验证表单两次:一次使用表单,一次使用单独的验证器。从性能的角度来看,这是一个坏主意。

                      我建议使用它的子级递归迭代表单类型以收集错误消息。

                      使用一些带有独占 IF 语句的建议方法

                      其他作者建议的一些答案包含相互排斥的 IF 语句,例如:if ($form-&gt;count() &gt; 0) 或 if ($form-&gt;hasChildren())。

                      据我所知,每个表单都可能有错误以及子级。我不是 Symfony Forms 组件方面的专家,但实际上您不会收到表单本身的一些错误,例如 CSRF 保护错误 或 额外字段 em> 错误。我建议删除这种分隔。

                      使用非规范化结果结构

                      一些作者建议将所有错误放在一个普通数组中。因此,表单本身及其子项的所有错误消息都将使用不同的索引策略添加到同一个数组中:基于数字的类型自身的错误和基于名称的子错误。我建议使用形式的规范化数据结构:

                      errors:
                          - "Self error"
                          - "Another self error"
                      
                      children
                          - "some_child":
                              errors:
                                  - "Children error"
                                  - "Another children error"
                      
                              children
                                  - "deeper_child":
                                      errors:
                                          - "Children error"
                                          - "Another children error"
                      
                          - "another_child":
                              errors:
                                  - "Children error"
                                  - "Another children error"
                      

                      这样结果可以很容易地在以后迭代。

                      我的解决方案

                      所以这是我对这个问题的解决方案:

                      use Symfony\Component\Form\Form;
                      
                      /**
                       * @param Form $form
                       * @return array
                       */
                      protected function getFormErrors(Form $form)
                      {
                          $result = [];
                      
                          // No need for further processing if form is valid.
                          if ($form->isValid()) {
                              return $result;
                          }
                      
                          // Looking for own errors.
                          $errors = $form->getErrors();
                          if (count($errors)) {
                              $result['errors'] = [];
                              foreach ($errors as $error) {
                                  $result['errors'][] = $error->getMessage();
                              }
                          }
                      
                          // Looking for invalid children and collecting errors recursively.
                          if ($form->count()) {
                              $childErrors = [];
                              foreach ($form->all() as $child) {
                                  if (!$child->isValid()) {
                                      $childErrors[$child->getName()] = $this->getFormErrors($child);
                                  }
                              }
                              if (count($childErrors)) {
                                  $result['children'] = $childErrors;
                              }
                          }
                      
                          return $result;
                      }
                      

                      我希望它会帮助别人。

                      【讨论】:

                      • @weaverryan 你能看看我的解决方案吗?它是有效的,还是有缺点或任何误解?谢谢!
                      【解决方案20】:

                      SYMFONY 3.1

                      我只是实现了一个静态方法来处理错误的显示

                      static function serializeFormErrors(Form\Form $form)
                      {
                          $errors = array();
                          /**
                           * @var  $key
                           * @var Form\Form $child
                           */
                          foreach ($form->all() as $key => $child) {
                              if (!$child->isValid()) {
                                  foreach ($child->getErrors() as $error) {
                                      $errors[$key] = $error->getMessage();
                                  }
                              }
                          }
                      
                          return $errors;
                      }
                      

                      希望能帮到你

                      【讨论】:

                        【解决方案21】:

                        对于 Symfony 2.1:

                        这是我将许多其他解决方案组合在一起的最终解决方案:

                        protected function getAllFormErrorMessages($form)
                        {
                            $retval = array();
                            foreach ($form->getErrors() as $key => $error) {
                                if($error->getMessagePluralization() !== null) {
                                    $retval['message'] = $this->get('translator')->transChoice(
                                        $error->getMessage(), 
                                        $error->getMessagePluralization(), 
                                        $error->getMessageParameters(), 
                                        'validators'
                                    );
                                } else {
                                    $retval['message'] = $this->get('translator')->trans($error->getMessage(), array(), 'validators');
                                }
                            }
                            foreach ($form->all() as $name => $child) {
                                $errors = $this->getAllFormErrorMessages($child);
                                if (!empty($errors)) {
                                   $retval[$name] = $errors; 
                                }
                            }
                            return $retval;
                        }
                        

                        【讨论】:

                          猜你喜欢
                          • 1970-01-01
                          • 1970-01-01
                          • 1970-01-01
                          • 1970-01-01
                          • 2021-04-10
                          • 1970-01-01
                          • 1970-01-01
                          • 1970-01-01
                          • 2013-07-23
                          相关资源
                          最近更新 更多