简体   繁体   中英

How to custom HTML form_errors in Symfony

I would like custom the render of form_errors in Symfony 3, because I would like obtain (in my Twig remplate) :

<div class="alert alert-danger">My error</div>

Instead of :

<ul><li>My error</li></ul>

It's possible ?

I tried this :

{{ form_errors(form.name) ? '<div class="alert alert-danger">' ~ form_errors(form.name) ~ '</div>' : ''  }}

But the HTML is not interpreted and it may not be very clean ..

And this (Recovery of vendor\\symfony\\symfony\\src\\Symfony\\Bridge\\Twig\\Resources\\views\\Form\\form_div_layout.html.twig line 307):

I overloaded:

{%- block form_errors -%}
    {%- if errors|length > 0 -%}
    <ul>
        {%- for error in errors -%}
            <li>{{ error.message }}</li>
        {%- endfor -%}
    </ul>
    {%- endif -%}
{%- endblock form_errors -%}

By :

{%- block form_errors -%}
{%- if errors|length > 0 -%}
<ul>
    {%- for error in errors -%}
        <li>{{ error.message }}</li>
    {%- endfor -%}
</ul>
{%- endif -%}
{%- endblock form_errors -%}

But the variable "error" is not defined

Thanks in advance for your help

Take a look at this website:

https://symfonycasts.com/screencast/symfony-forms/form-theme-create#play

You need to modify below file

vendor/symfony/symfony/src/Symfony/Bridge/Twig/Resources/views/Form/bootstrap_3_layout.html.twig

and search for the {% block form_errors -%} block to modify it.

you can look here for more informations:

https://codereviewvideos.com/course/beginner-s-guide-to-symfony-3-forms/video/styling-and-customising-using-form-fragments

But this is not the right method, the good one is to override this file by copy that block into another twig template, modify it and call this template into the twig template of your page.

Here are the explanations:

https://symfonycasts.com/screencast/symfony-forms/form-theme-create#play

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM