Reputation: 491
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.
Upvotes: 1
Views: 1568
Reputation: 2595
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.
Upvotes: 4