I lose the association of errors in the form field in Symfony2

My check looks like

Acme\UserBundle\Entity\User: constraints: - \Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity: { fields:username, message: "Username already in use" } - \Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity: { fields:email, message: "Email address already in use" } properties: username: - NotBlank: ~ - MinLength: { limit: 2, message: "Your username must have at least {{ limit }} characters." } email: - Email: message: The email "{{ value }}" is not a valid email. checkMX: true 

My controller is like:

 $form = $this->createForm(new RegistrationType()); $form->bindRequest($request); if ($form->isValid()) { //... save to db }else{ $errors = $form->getErrors(); //... pass the errors back as json } 

I am trying to create a user registration controller that is sent through an ajax request. However, when errors in the check are triggered, the $error variable looks like this:

 [2011-11-07 19:19:44] app.INFO: array ( 0 => Symfony\Component\Form\FormError::__set_state(array( 'messageTemplate' => 'Email address already in use', 'messageParameters' => array ( ), )), 1 => Symfony\Component\Form\FormError::__set_state(array( 'messageTemplate' => 'Your username must have at least {{ limit }} characters.', 'messageParameters' => array ( '{{ value }}' => '1', '{{ limit }}' => 2, ), )), ) [] [] 

The problem is that I do not know in which field this error corresponds. Is there any way to find this data so that when sending a json response I can associate the error message with the corresponding field.

+7
source share
2 answers

I think you can request each field separately, for example:

$form->get('username')->getErrors()

So you can create an array this way:

 $errors['username'] = $form->get('username')->getErrors(); $errors['email'] = $form->get('email')->getErrors(); 

You may be able to automate everything:

 $fields = $form->getChildren(); foreach ( $fields as $field ) { $errors[$field->getName()] = $field->getErrors(); } 

I think that the getName function should return the name of the field when the form is called in children. Someone else might have a more efficient way though ...

+6
source

I think the accepted answer is already outdated, there is no getChildren() method.

 $errors = []; foreach ($form->all() as $field) { if ($field->getErrors()->count() > 0) { $fieldName = $field->getName(); $errors[$fieldName] = []; foreach ($field->getErrors() as $error) { $errors[$fieldName][] = $error->getMessage(); } } } 

After all, if you want to access form fields from a generated FormView , which will give you the full names of the input fields:

 $errors = []; foreach ($form->createView()->children as $field) { if ($field->vars['errors']->count() > 0) { $fieldName = $field->vars['full_name']; $errors[$fieldName] = []; foreach ($field->vars['errors'] as $error) { $errors[$fieldName][] = $error->getMessage(); } } } 
+3
source

All Articles