Symfony2 shows form errors near the fields and at the top of the form

In Symfony2, how would I start showing form errors next to each AND field at the top of the form using twig templates?

At that moment, I was able to get only one or the other by setting error_bubbling to true or false for each field ...

thanks

+4
source share
2 answers

The solution I can offer is to make a second, explicit, check of your object and send errors to your template. Thus, the first, implicit, validation is performed inside the form object, and errors are bound to fields (do not use error bubbling). The second check will give you an iterator about errors, and you can pass this iterator to your template, which will be displayed at the top of the form. Then you will have errors in each field, as well as at the top of the forms.

I suggest you this based on this StackOverflow question. Check out this specific answer.

Here is a sketch of the code for the controller (I have not tested anything):

 // Code in a controller public acmeFormAction(...) { // Form and object code // Get a ConstraintViolationList $errors = $this->get('validator')->validate( $user ); return $this->render('AcmeTaskBundle:Default:new.html.twig', array( 'form' => $form->createView(), 'errors' => errors, )); } 

And the code in the template:

 {# Code in a twig template #} <ul id="error-list"> {% for error in errors %} <li> error.message </li> {% endfor %} </ul> {# Display your form as usual #} 

If you remember correctly, there is a way to get all errors from the form and still have errors set in each field. From my memory, this is a special attribute in the form that looks like form.errors . But I can’t remember or find information about it. So, at the moment, this is the best approach I can find.

+2
source

What you have to do is use form errors that are already available as vars, as described here:

fooobar.com/questions/678226 / ...

Please take a look at the comment:

Use vars.errors in new versions or just dump the form field to see the attributes. Because this part depends on the version of Symfony.

0
source

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


All Articles