Reputation: 13
To integrate this in Twig:
<label class="control-label" for="lastname">Last Name:</label>
<div class="controls">
<input type="text" id="firstname" name="firstname">
<span class="help-block">{{ form_errors(form.firstname) }}</span>
</div>
I used the following code snippet:
{{ form_label(form.firstname, null, {'label_attr': {'class': 'control-label'}}) }}
<div class="controls">
{{ form_widget(form.firstname) }}
<span class="help-block">{{ form_errors(form.firstname) }}</span>
</div>
And everything worked fine.
But my question is ...
Is it possible to wrap a form_widget with a form_label in Twig? The final result should then be similar to:
<label class="radio" for="dn">
<input type="radio" id="dn" name="spotlight" value="1"> Test 1
</label>
<label class="radio" for="gn">
<input type="radio" id="gn" name="spotlight" value="1"> Test 2
</label>
<span class="help-block">Errors</span>
Can I use anything else than form_label
and form_widget
to achive the same result?
Upvotes: 1
Views: 1321
Reputation: 10513
You can change the display of the form_row()
output in only one file:
{% form_theme form _self %}
{% block form_row %}
<div class="form_row">
{% 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 %}
<label{% for attrname, attrvalue in label_attr %} {{ attrname }}="{{ attrvalue }}"{% endfor %}>{{ label|trans({}, translation_domain) }}
{% endif %}
{{ form_widget(form) }}
{% if label is not sameas(false) %}
</label>
{% endif %}
{{ form_errors(form) }}
</div>
{% endblock form_row %}
And display your field:
{{ form_row(form.firstname) }}
The <label>
is now opening before the field and closing after the field.
I took the original code from default theme and use the cookbook entry Form Theming in Twig > Method 1: Inside the same Template as the Form.
If you want to apply your idea to all of your fields, consider using form customization in order to change the display of {{ form_row(....) }}
in all your bundle.
Upvotes: 1