Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access errors in Symfony2 controller for AJAX submitted form

Problem 1

I'd like to build a registration form via ajax submission. Registration works is the $form->isValid(). However, if the form fails registration I need to return these errors via ajax.

if ($form->isValid()) {

}else{
    $errors = $form->getErrors();
    // return some json encoded errors here
}

$form->getErrors() returns an empty array even though the form did not validate (in this case I am testing with a username that is too short).

Problem 2

The second problem I have is that if the form validates but there is still an error. For example a unique field that someone tries to submit the same value for.

if ($form->isValid()) {

    $em = $this->getDoctrine()->getEntityManager();
    $em->persist($form->getData());
    $em->flush();

    // error could be a username submitted more than once, username is unique field

}else{
    // ...
}

How can I catch that error and return it via json?

like image 208
ed209 Avatar asked Nov 06 '11 18:11

ed209


2 Answers

Problem 1

In your form builder you can use error_bubbling to move the errors into your form object. When you specify the field, pass it in as an option like this:

$builder->add('username','text', array('error_bubbling'=>true));

and you can access errors in your form object like this:

$form->getErrors();

Outputs something like

array (
  0 => 
  Symfony\Component\Form\FormError::__set_state(array(
     'messageTemplate' => 'Your username must have at least {{ limit }} characters.',
     'messageParameters' => 
    array (
      '{{ value }}' => '1',
      '{{ limit }}' => 2,
    ),
  )),
) [] []

fyi: If you are using Form/Type's you can't set error_bubbling as a default value, it has to be assigned to each field.

Useful link: http://symfony.com/doc/2.0/reference/forms/types/text.html#error-bubbling

Problem 2

http://symfony.com/doc/2.0/reference/constraints/UniqueEntity.html

like image 169
ed209 Avatar answered Nov 15 '22 07:11

ed209


Problem 1

The errors aren't on the form itself. Form::getErrors would only return errors if there were any on the form object itself. You need to traverse the form and check for errors on each child.

Form::isValid on the contrary just traverses the children and check if any of them are invalid.

Problem 2

If there still are "errors" after validation, that means that your validation isn't complete. If your application requires a non-standard constraint, you should just go ahead and write a custom constraint. See the cookbook entry on writing custom validator constraints for more information.

like image 36
Magnus Nordlander Avatar answered Nov 15 '22 07:11

Magnus Nordlander