Here's my saveAction
code (where the form passes the data to)
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();
}
My question is: how do I get the errors if $form->isValid()
returns false
?
You have two possible ways of doing it:
{{ form_errors(form) }}
within template file$form->getErrors()
Based on @Jay Seth's answer, I made a version of FormErrors class especially for Ajax Forms:
Usage (e.g. in your action):
Symfony version: 2.8.4
Example JSON response:
The error object contains the "key" field, which is the id of the input DOM element, so you can easily populate error messages.
If you have child forms inside the parent, don't forget to add the
cascade_validation
option inside the parent form'ssetDefaults
.Symfony 2.3 / 2.4:
This function get's all the errors. The ones on the form like "The CSRF token is invalid. Please try to resubmit the form." as well as additional errors on the form children which have no error bubbling.
To get all errors as a string:
Symfony 2.5 / 3.0:
Docs:
https://github.com/symfony/symfony/blob/master/UPGRADE-2.5.md#form https://github.com/symfony/symfony/blob/master/UPGRADE-3.0.md#form (at the bottom:
The method Form::getErrorsAsString() was removed
)SYMFONY 3.1
I simply implemented a static method to handle the display of errors
Hoping to help
Below is the solution that worked for me. This function is in a controller and will return a structured array of all the error messages and the field that caused them.
Symfony 2.0:
Symfony 2.1 and newer:
To get proper (translatable) messages, currently using SF 2.6.3, here is my final function (as none of above's seem to work anymore):
as the Form::getErrors() method now returns an instance of FormErrorIterator, unless you switch the second argument ($flatten) to true. (It will then return a FormError instance, and you will have to call the getMessage() method directly, without the current() method:
)
The most important thing is actually to set the first argument to true in order to get the errors. Leaving the second argument ($flatten) to his default value (true) will return FormError instances, while it will return FormErrorIterator instances when set to false.