Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I'm losing the association of an error to a form field in Symfony2

My validation 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 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'm trying to build a user registration controller that is submitted via ajax request. However, when errors in validation are triggered, the $error variable looks like:

[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 I have no idea which field that error corresponds to. Is there some way to find that data so that when I send the json response, I can associate the error message with the relevant field.

like image 726
ed209 Avatar asked Nov 07 '11 19:11

ed209


1 Answers

I think that you can query each field individually for instance:

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

So you could build up an array that way:

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

You may be able to automate things though:

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

I think that the getName function should return the field name when called on children of the form its self. Someone else may have a more efficient way though...

like image 121
Kasheen Avatar answered Oct 12 '22 12:10

Kasheen