I have this code:
{% for key, customField in customFields %}
{{ form_widget(formVirtualTerminal['cf_' ~ key], { 'attr': {'placeholder': customField['FieldDisplayName'], 'name': customField['FieldName'], 'class' : 'row no-gutters mb-3'} }) }}
{% endfor %}
which traverses an array and outputs some fields for it. However, for reasons unknown to me, a form-control
class is generated into all these fields and that ruins the design of the page.
In this question (delete form-control in form-row symfony/twig) it's mentioned that this is part of a default Bootstrap theme and they discuss how this theme can be deactivated on application level.
However, I prefer not to do such radical changes if possible. I would like to tell Twig not to add classes.
The following is a hack which solves the problem by removing that class:
$("#custom-text-field-container .form-control").removeClass("form-control");
However, I would like to avoid writing Javascript to remove classes from fields which should never had that class in the first place.
Is there a way to tell twig not to write form-control
class into these text fields?
You can't "tell twig not to add classes".
The form_widget
does not accept any parameter to remove a class or attribute that will be later applied by the theme.
Basically, it has no control over what the template does, it only passes the template whatever parameters you want, and it's up to the form template how to use that information.
E.g. for HTML classes, the usual approach is simply to merge whatever classes you pass with whatever classes the template has set by default.
A simple recourse would be to create to your theme based on the form theme you are using (which seems to be 'bootstrap_4_layout.html.twig')
You'd need to rewrite only the parts that hinder you, leaving everything else as it is.
E.g. a "complete" new theme could be as short as:
{# templates/form/your_theme.html.twig #}
{% use 'bootstrap_4_layout.html.twig' %}
{% block form_widget_simple -%}
{% if type is not defined or type != 'hidden' %}
{%- set attr = attr|merge({class: (attr.class|default('') ~ (type|default('') == 'file' ? ' custom-file-input' : ''))|trim}) -%}
{% endif %}
{%- if type is defined and (type == 'range' or type == 'color') %}
{# Attribute "required" is not supported #}
{%- set required = false -%}
{% endif %}
{{- parent() -}}
{%- endblock form_widget_simple %}
This is almost the same form_widget_simple
block as the original, I simply removed the form-control
class that is merged with the classes you can pass through.
You can use this form only in the templates you want this custom theme by doing this in the appropriate template:
{% form_theme form 'form/your_theme.html.twig' %}
Or if you want to use it by default in all forms in your application:
# config/packages/twig.yaml
twig:
form_themes: ['form/your_theme.html.twig']
# ...