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
?
Translated Form Error Messages (Symfony2.1)
I have been struggling a lot to find this information so I think it's definitely worth adding a note on translation of form errors.
@Icode4food
answer will return all errors of a form. However, the array that is returned does not take into account either message pluralization or translation.You can modify the foreach loop of
@Icode4food
answer to have a combo:Here it is:
This answer has been put together from 3 different posts:
Use the Validator to get the errors for a specific entity
API reference:
You can also use the validator service to get constraint violations:
For Symfony 2.1 onwards for use with Twig error display I altered the function to add a FormError instead of simply retrieving them, this way you have more control over errors and do not have to use error_bubbling on each individual input. If you do not set it in the manner below {{ form_errors(form) }} will remain blank:
For Symfony 2.1:
This is my final solution putting in together many others solutions:
If you're using custom validators, Symfony doesn't return errors generated by those validators in
$form->getErrors()
.$form->getErrorsAsString()
will return all the errors you need, but its output is unfortunately formatted as a string, not an array.The method you use to get all the errors (regardless of where they came from), depends on which version of Symfony you're using.
Most of the suggested solutions involve creating a recursive function that scans all child forms, and extracts the relevant errors into one array. Symfony 2.3 doesn't have the
$form->hasChildren()
function, but it does have$form->all()
.Here is a helper class for Symfony 2.3, which you can use to extract all errors from any form. (It's based on code from a comment by yapro on a related bug ticket in Symfony's github account.)
Calling code: