Search code examples
phphtmlsymfonyvalidationsymfony-2.8

Symfony Customize form errors css


I'm using symfony 2.8. In registration form, when I submit form with empty fields, it is showing validation errors in

  • tag. It is really making the UI looks bad. How can I change the css of each validation error messages.

    {{ form_start(form, {'method': 'post', 'action': path('fos_user_registration_register'), 'attr': {'class': 'fos_user_registration_register','novalidate': 'novalidate'}}) }}
                <div class="form-group">
                    {{ form_row(form.name) }}
                </div>
                <div class="form-group">
                    {{ form_row(form.email) }}
                </div>
                <div class="form-group">
                    {{ form_row(form.username) }}
                </div>
                <div class="form-group">
                    {{ form_row(form.plainPassword.first) }}
                </div>
                <div class="form-group">
                    {{ form_row(form.plainPassword.second) }}
                </div>
                <div>
                    <input type="submit" class="btn btn-primary" value="{{ 'registration.submit'|trans }}" />
                </div>
                {{ form_end(form) }}
    

  • Solution

  • You are rendering form fields using form_row widget which renders label, field & related error to do custom styling you can render your fields and their labels and errors individually like

    {{ form_start(form, {'method': 'post', 'action': path('fos_user_registration_register'), 'attr': {'class': 'fos_user_registration_register','novalidate': 'novalidate'}}) }}
    
        {{ form_label(form.email) }}
    
        <div class="some_class">{{ form_errors(form.email) }} </div>
    
        {{ form_widget(form.email) }}
    
    {{ form_end(form) }}
    
    <style type="text/css">
    
    .some_class{
     /* write custom styling rules here */
    }
    
    </style>
    

    Or get all errors in one place like

    {# render any "global" errors #}
    {{ form_errors(form) }}
    

    Reference: Twig Template Form Function and Variable Reference