5

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

At the moment I only managed to get one or the other, by setting error_bubbling to true or false on each and every field...

Thanks

jfoucher
  • 2,251
  • 2
  • 21
  • 29

2 Answers2

2

A solution I can propose you is to do a second, explicit, validation of your object and sending errors to your template. This way, the first, implicit, validation is done within the form object and errors are bound to fields (do not use error bubbling). The second validation will give you an iterator on errors and you can pass that iterator to your template to be displayed at the top of the form. You will then have the errors aside each field and also at the top of the forms.

I suggest you this based on this question on StackOverflow. Check this particular answer.

Here a sketch of the code for the controller (I did not test 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 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 a remember correctly, there is a way to retrieve all errors from the form and still having the errors set on each field. From my memory, it's a special attribute on the form view something like form.errors. But I can't remember or find any info about this. So, for now, this is the best approach I can find.

Community
  • 1
  • 1
Matt
  • 10,633
  • 3
  • 46
  • 49
  • Doing a second, explicit validation sounds not good, if we look at it global-wise. Let's assume we have 50 form's in our app.. yeah. Take a look at my answer. – Rafał Mnich Mar 12 '17 at 13:23
0

What you should do is use form errors which are available already in view vars like described here:

https://stackoverflow.com/a/13047952/1041895

Please take a look at the comment:

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

Community
  • 1
  • 1
Rafał Mnich
  • 516
  • 4
  • 11