symfonytwigsymfony-forms

How to override form_errors() from twig Symfony 5.2?


How to override the form field validation error template in Symfony 5.2?

I have a form like this in twig

        {{ form_start(registrationForm) }}
            name:<br />
            {{ form_row(registrationForm.name) }}
            family_name:<br />
            {{ form_row(registrationForm.family_name) }}
            Email:<br />
            {{ form_row(registrationForm.email) }}
            password:<br />
            {{ form_row(registrationForm.password) }}
            <br />
            <div class="text-center"><button type="submit" class="site-btn">registration</button></div>
        {{ form_end(registrationForm) }}

In case of an error in the validation of the email field, this is the layout

<div>
  <ul>
    <li>There is already an account with this email</li>
  </ul>
  <input type="text" id="registration_form_email" name="registration_form[email]" required="required" maxlength="180" class="register-form-input" autocomplete="off" value="asd">
</div>

The problem is that the layout with a form validation error

  <ul>
    <li>There is already an account with this email</li>
  </ul>

Taken from the standard template symfony, but I want to use my own template when a form field validation fails.

I turned to the documentation for clarifications this and this but to be honest, it confused me more, I just realized that this form can be stylized somehow in the template, but I didn't understand.

How to make your own template for displaying field validation error for a form?

As a result, I want to get such a layout:

<div>
  <b>There is already an account with this email</b> <br>
  <input type="text" id="registration_form_email" name="registration_form[email]" required="required" maxlength="180" class="register-form-input" autocomplete="off" value="asd">
</div>

Solution

  • foundation_5_layout.html.twig extends form_div_layout.html.twig, i havn't see form_errors was in form_div_layout too, but principle is same.

    Don't make a copy, create a template "errors.html.twig" by example, create a block form_errors with your code you want, and in your form template, call it with

    {% form_theme form 'path/to/errors.html.twig' %}
    

    Is it clearer :) ? It's just an override of twig blocks