Reputation: 883
As the title says I'm trying to attach the bootstrap form-control
class to each generated input or widget as they're called in twig. I'm trying to use form theming to be able to easily make multiple forms that look the same way.
I'm trying it in the same way as I've managed to get it to work with the labels. But because the form_widget
block is inherited by other blocks (form_widget_simple
& form_widget_compound
).
Here's the code that's giving me trouble
{% block form_widget %}
{% spaceless %}
<div class="col-sm-10">
{% set attr = attr|merge({'class': (attr.class|default('') ~ ' form-control ')|trim}) %}
{% if compound %}
{{ block('form_widget_compound') }}
{% else %}
{{ block('form_widget_simple') }}
{% endif %}
</div>
{% endspaceless %}
{% endblock form_widget %}
Also, the col-sm-10
div is only rendered on widgets that inherit from form_widget_simple
and not for the compound widgets.
I don't know if I've explained this clearly enough but any help would be very appreciated.
{% block form_label %}
{% spaceless %}
{% if label is not sameas(false) %}
{% if not compound %}
{% set label_attr = label_attr|merge({'for': id}) %}
{% endif %}
{% if required %}
{% set label_attr = label_attr|merge({'class': (label_attr.class|default('') ~ ' required ')|trim}) %}
{% endif %}
{% if label is empty %}
{% set label = name|humanize %}
{% endif %}
{% set label_attr = label_attr|merge({'class': (label_attr.class|default('') ~ ' col-sm-2 control-label ')|trim}) %}
<label {% for attrname, attrvalue in label_attr %} {{ attrname }}="{{ attrvalue }}" {% endfor %}>{{ label|trans({}, translation_domain) }}</label>
{% endif %}
{% endspaceless %}
{% endblock form_label %}
Upvotes: 2
Views: 455
Reputation: 2063
You have to edit the form_row
block, it will modify both simple and compound widget.
{% block form_row -%}
{{- form_label(form) -}}
<div class="col-sm-10">
{{- form_widget(form) -}}
{{- form_errors(form) -}}
</div>
{%- endblock form_row %}
EDIT: For the control-form class
You can add it in the block widget_attributes
{% block widget_attributes -%}
{% set class = 'form-control' %}
id="{{ id }}" name="{{ full_name }}"{% if read_only %} readonly="readonly"{% endif %}{% if disabled %} disabled="disabled"{% endif %}{% if required %} required="required"{% endif %}{% if max_length %} maxlength="{{ max_length }}"{% endif %}{% if pattern %} pattern="{{ pattern }}"{% endif %}
{% for attrname, attrvalue in attr %}{% if attrname in ['placeholder', 'title'] %}{{ attrname }}="{{ attrvalue|trans({}, translation_domain) }}" {% elseif attrname in ['class'] %} {% set class = class ~ ' ' ~ attrvalue %} {% else %}{{ attrname }}="{{ attrvalue }}" {% endif %}{% endfor %}
class="{{ class }}"
{%- endblock widget_attributes %}
The last two lines are pretty intense to read, hope you get the picture.
Upvotes: 2