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
?
I came up with this solution. It works solid with the latest Symfony 2.4.
I will try to give some explanations.
Using separate validator
I think it's a bad idea to use separate validation to validate entities and return constraint violation messages, like suggested by other writers.
You will need to manually validate all the entities, specify validation groups, etc, etc. With complex hierarchical forms it's not practical at all and will get out of hands quickly.
This way you will be validating form twice: once with form and once with separate validator. This is a bad idea from the performance perspective.
I suggest to recursively iterate form type with it's children to collect error messages.
Using some suggested methods with exclusive IF statement
Some answers suggested by another authors contain mutually exclusive IF statements like this:
if ($form->count() > 0)
orif ($form->hasChildren())
.As far as I can see, every form can have errors as well as children. I'm not expert with Symfony Forms component, but in practice you will not get some errors of the form itself, like CSRF protection error or extra fields error. I suggest to remove this separation.
Using denormalized result structure
Some authors suggest to put all errors inside of a plain array. So all the error messages of the form itself and of it's children will be added to the same array with different indexing strategies: number-based for type's own errors and name-based for children errors. I suggest to use normalized data structure of the form:
That way result can be easily iterated later.
My solution
So here's my solution to this problem:
I hope it'll help someone.
$form->getErrors() works for me.
The function for symfony 2.1 and newer, without any deprecated function:
Translated Form Error Messages (Symfony2.3)
My version of solving the problem:
/src/Acme/MyBundle/Resources/config/services.yml
/src/Acme/MyBundle/Form/FormErrors.php
/src/Acme/MyBundle/Controller/DefaultController.php
In Symfony 2.5 you can get all fields errors very easy:
SYMFONY 3.X
Other SF 3.X methods given here did not work for me because I could submit empty data to the form (but I have NotNull/NotBlanck constraints). In this case the error string would look like this :
Which is not very usefull. So I made this:
Which would return that :
For Symfony 3.2 and above use this,
Use str_replace if you want to get rid of the annoying 'Error:' text in each error description text.