1

I am trying to implement bootstrap styles when the form has errors, and I have succeeded ... but in a very tedious way. For example:

<div class="form-group">
    {{ form_label(form.name) }}
    {{ form_widget(form.name) }}
    {{ form_errors(form.name) }}
</div>

When there is an error in the form, I would like to add the "has-danger" class to the corresponding divs to customize the view. In this way it would be like this:

<div class="form-group has-danger">
    {{ form_label(form.name) }}
    {{ form_widget(form.name) }}
    {{ form_errors(form.name) }}
</div>

I have come up with a not very pretty way to do it:

<div class="form-group {% if form.name.vars.errors|length > 0 %}has-danger{% endif %}">

The problem is that I would have to add this code to all the fields of all the forms on my website, which I do not see well.

Any ideas? Thank you.

1 Answer 1

4

You should have a look at form themes as they already integrate Bootstrap CSS. Most probably you just need to use bootstrap_4_layout.html.twig instead of form_div_layout.html.twig as form theme in config/packages/twig.yaml:

twig:
    ...
    form_themes:
        - bootstrap_4_layout.html.twig

If that's not enough you can customise each fragment of the forms as you prefer and then use it in your forms. More aspects and info in the same section of the docs.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.