Symfony2 controller access errors for submitted AJAX form

Problem 1

I would like to create a registration form through an ajax view. Registration work - $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, although the form has not been verified (in this case I am testing with a user name that is too short).

Problem 2

The second problem is that if the form is checked, but there is still an error. For example, a unique field in which someone is trying to represent the same value.

 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 this error and return it via json?

+6
source share
2 answers

Problem 1

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

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

and you can access the errors in the form object as follows:

 $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 use Form / Type, you cannot set error_bubbling as the default value, it must 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

+7
source

Problem 1

Errors do not apply to the form itself. Form::getErrors will return errors only if they were on the form object itself. You need to go through the form and check for errors for each child.

Form::isValid on the contrary, simply traverses the children and checks to see if any of them are.

Problem 2

If there are still β€œerrors” after the check, it means that your check is not completed. If your application requires a custom constraint, you just have to go to the custom constraint. For more information, see a cookbook entry when writing custom validator constraints .

+4
source

Source: https://habr.com/ru/post/900896/


All Articles