Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 show form errors next to fields and at top of form

Tags:

php

symfony

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

like image 474
jfoucher Avatar asked Nov 04 '22 10:11

jfoucher


1 Answers

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.

like image 83
Matt Avatar answered Nov 09 '22 18:11

Matt