Reputation: 410
I would like add a CSS class on a form_widget() when errors (specific to field) happen.
For now, I have this code :
{{ form_widget(form.firstName, {'attr': {'class': 'text-input'}}) }}
It generates this HTML code :
<input type="text" id="userbundle_member_firstName" name="userbundle_member[firstName]" required="required" class="text-input" />
It's good but I want when error(s) happen (exemple the value is too short), a css class will added. So, I want to have something like that :
<input type="text" id="userbundle_member_firstName" name="userbundle_member[firstName]" required="required" class="text-input error-input" />
I tried searching solution on the doc (especially here), but I have not been able to do what I want.
Thank you for your help :D !
Upvotes: 1
Views: 3004
Reputation: 16649
Tell Twig about your custom form's templates:
app/config/config.yml
twig:
debug: %kernel.debug%
strict_variables: %kernel.debug%
form:
resources:
- 'YourBundle::form.html.twig'
And override them (check vendor/symfony/symfony/src/Symfony/Bridge/Twig/Resources/views/Form):
src/YourBundle/Resources/views/form.html.twig
{% block form_widget_simple %}
{% if form.vars.errors|length > 0 %}
{% set class = attr.class is defined ? attr.class ~ ' error' : 'error' %}
{% set attr = attr|merge({'class': class}) %}
{% endif %}
{% spaceless %}
{% set type = type|default('text') %}
<input type="{{ type }}" {{ block('widget_attributes') }} {% if value is not empty %}value="{{ value }}" {% endif %}/>
{% endspaceless %}
{% endblock form_widget_simple %}
UPDATE
The method described above will change the rendering of all the form fragments, if you only need to change some form then you can do it locally, just read the docs (https://symfony.com/doc/current/book/forms.html#form-theming)
Upvotes: 4