Is there a way to wrap label around input in symfony2?

forms, label, symfony, twig

Solution

I think this is what you are looking for: http://symfony.com/doc/current/book/templating.html#overriding-bundle-templates

You can override any of the default twig templates by creating another file with the same name in your app/resources folder.

In your case you want to override the form_div_layout.html.twig template, copy it from the bundle to app/Resources/TwigBundle/views/Form/form_div_layout.html.twig, customize away and symfony will use that rather than the default.

EDIT: Once you have overridden the template you could modify the `{% block checkbox_widget %}` to have the input wrapped with the label tags using the twig vars

<label{% for attrname,attrvalue in attr %} {{attrname}}="{{attrvalue}}"{% endfor %}>
  {{label|trans }} 
  <input type="checkbox" {{ block('widget_attributes') }}{% if value is defined %} value="{{ value }}"{% endif %}{% if checked %} checked="checked"{% endif %} /> 
</label> 

You will also need to remove the 'generic_label' definition, meaning every other block requires modifications.

Problem

Question about symfony2 form component and its templating: I've got a bunch of checkboxes to style (about 10 in one form row). Usually I use `<label>` tag this way: `<label><input/> some text</label>` but I can't find a way to change it in the form template (form_div_layout.html.twig). I can't even find a way to wrap any tag around input widget and its label and I always end up with markup like this: `<input/> <some_tag><label>some text</label></some_tag>` or `<some_tag><input/></some_tag> <label>some text</label>` which is not very useful, to say the least... Googled quite a bit, but couldn't find an answer.

Original source