2013-03-22 42 views
1

有一个关于如何正确输出表单提交错误在Symfony2时,他们从ajax响应回来的问题。Symfony2 ajax树枝形成错误

我张贴通过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中,我可以设置这些错误的格式,以便它们在返回到树枝模板时看起来像样的?我想它看起来像这样,但我不知道它怎么做:

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) 

非常感谢您的帮助!

+0

怎么样'$错误= strtr函数的效率($形式 - > getErrorsAsString(),阵列( '\ n'=> '
')); '? – 2013-03-22 23:38:18

回答

5

,您应该使用$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); 
+0

非常感谢! – LargeTuna 2013-03-23 17:28:44

0

我说最干净的解决方案是实现JMSSerializerBundlehttp://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; 
    }