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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With