【问题标题】:Symfony2 ajax twig form errorsSymfony2 ajax twig 表单错误
【发布时间】:2013-03-12 22:56:06
【问题描述】:

有一个问题,当它们从 ajax 响应返回时,如何在 Symfony2 中正确输出表单提交错误。

我正在通过 ajax 发布表单,如果表单填写不正确,它将使用以下代码发回错误的响应...

 $errors = $form->getErrorsAsString();
 $return = array("responseCode"=>200, "responseVal"=>"Error", "errorReport"=>$errors);

这将创建一个错误数组和其他变量,如下所示:

 {"responseCode":200,"responseVal":"Error","errorReport":"ERROR: Name cannot be blank.\nERROR: Address cannot be blank.\nERROR: City cannot be blank.\nERROR: State cannot be blank.\nERROR: Zip cannot be blank.\nERROR: Phone cannot be blank.\nERROR: Email cannot be blank.\nname:\n    No errors\naddress:\n    No errors\ncity:\n    No errors\nstate:\n    No errors\nzip:\n    No errors\nemail:\n    No errors\nfax:\n    No errors\nphone:\n    No errors\n"}

然后我使用 jQuery 将错误写入 div,如下所示:

 $("#errorReport").html(data.errorReport);

这给了我一个包含以下内容的 div:

 ERROR: Name cannot be blank. ERROR: Address cannot be blank. ERROR: City cannot be blank. ERROR: State cannot be blank. ERROR: Zip cannot be blank. ERROR: Phone cannot be blank. ERROR: Email cannot be blank. name: No errors address: No errors city: No errors state: No errors zip: No errors email: No errors fax: No errors phone: No errors

这看起来很俗气。在 Twig 或 Symfony 中是否有我可以格式化这些错误,以便在将它们传递回 twig 模板时看起来像样?我希望它看起来像这样,但我只是不知道它是如何完成的:

 Name cannot be blank. 
 Address cannot be blank. 
 City cannot be blank. 
 State cannot be blank. 
 Zip cannot be blank. 
 Phone cannot be blank. 
 Email cannot be blank. 

 (any of the "No errors" would not be shown)

非常感谢您的帮助!!!

【问题讨论】:

  • $errors = strtr($form->getErrorsAsString(), array('\n' => '<br />')); 怎么样?

标签: php jquery ajax symfony twig


【解决方案1】:

您应该使用$form->getErrors() 方法而不是$form->getErrorsAsString(); getErrors 函数返回可用于创建错误消息的FormError 对象

所以代码看起来像这样

$errors = $form->getErrors();
$errorCollection = array();
foreach($errors as $error){
       $errorCollection[] = $error->getMessageTemplate()
}
$return = array("responseCode"=>200, "responseVal"=>"Error", "errorReport"=>$errorCollection);

【讨论】:

    【解决方案2】:

    我想说最干净的解决方案是实现 JMSSerializerBundle (http://jmsyst.com/bundles/JMSSerializerBundle),它使用以下类:

    https://github.com/schmittjoh/serializer/blob/6bfebdcb21eb0e1eb04aa87a68e0b706193b1e2b/src/JMS/Serializer/Handler/FormErrorHandler.php

    然后在您的控制器中:

            // ...
            if ($request->isXMLHttpRequest()) {
            $jsonResponse = new JsonResponse();
    
            $serializer = $this->container->get('jms_serializer');
            $form = $serializer->serialize($form, 'json');
    
            $data = array('success' => false,
                           'errorList' => $form);
    
            $jsonResponse->setData($data);
    
            return $jsonResponse;
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-28
      • 2012-08-06
      • 2023-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-08
      • 1970-01-01
      相关资源
      最近更新 更多