Search code examples
formssymfony

How to render a form error in red color?


Using Symfony3 && PhpStorm.2016.3.2 on Ubuntu 16.04

I have a form made in Twig, here is the section that interest me:

<div class="row">
    <div class="input-field col s12 validate" id="icon_telephone" type="tel">
          {{ form_errors(form) }}
          {% if form.vars.errors|length %}
            { form_row(
            form.authorPhone,
            form.authorPhone.vars|merge({'attr': {'autofocus': null}})
           )
          }}
          {% else %}
             {{ form_row(form.authorPhone) }}
          {% endif %}
     </div>
</div>

I would like to "colorize" the error in Red as an example, without actually using customize form rendering of Symfony which force me to create a view etc..

So I wanted to know if there is a way to actually just turn the error red without industrializing the process.


Solution

  • Making something red is styling so you should be doing that via CSS. Add a css file to your form template and you can customize the rendering of your form errors like so:

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

    And css

    .error-message{
       color: red;
    }
    

    Symfony doc article: https://symfony.com/doc/current/form/form_customization.html#customizing-error-output

    Your final twig template would look like this:

    <div class="row">
        <div class="input-field col s12 validate" id="icon_telephone" type="tel">
              {{ form_errors(form) }}
              {% if form.vars.errors|length %}
                { form_row(
                form.authorPhone,
                form.authorPhone.vars|merge({'attr': {'autofocus': null}})
               )
              }}
              {% else %}
                 {{ form_row(form.authorPhone) }}
              {% endif %}
         </div>
    </div>
    
    <link rel="stylesheet" href="{{ asset('bundles/mybundle/css/style.css') }}" />
    
    {% block form_errors %}
        {% spaceless %}
            {% if errors|length > 0 %}
            <ul>
                {% for error in errors %}
                    <li class="error-message">{{ error.message }}</li>
                {% endfor %}
            </ul>
            {% endif %}
        {% endspaceless %}
    {% endblock form_errors %} 
    

    You override the form_errors block wich is what symfony will use when you call {{ form_errors(form) }}.

    If you wan't the simplest solution just inspect you errors in the browser find the right selector and apply css without customizing the form rendering in twig.

    For the stylesheet, create the file under Resources/public/css then execute app/console assets:install