2013-03-22 71 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; 
    }