Got a question about how to properly output form submission errors in Symfony2 when they come back from an ajax response.
I am posting a form via ajax, if the form is not filled in correctly, it will send back a reponse with the errors using the following code...
$errors = $form->getErrorsAsString();
$return = array("responseCode"=>200, "responseVal"=>"Error", "errorReport"=>$errors);
This will create an array of errors and other variables like so:
{"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"}
I am then using jQuery to write the errors to a div, like so:
$("#errorReport").html(data.errorReport);
This gives me a div with the following content:
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
This looks really tacky. Is there anyway in Twig or Symfony that I can format these errors so that it looks presentable when they are passed back to the twig template? I'd like it to look like this, but I just don't know how its done:
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)
Thanks so much for your help!!!
$errors = strtr($form->getErrorsAsString(), array('\n' => '<br />'));
? – Adam Elsodaney