I have a formbuilder form with a multiple choice list of countries. When I render them on my form like this:
{{ form_widget(edit_form.countries) }}
They appear like this:
<input type="checkbox" name="..." value="AD" /><label for="...">Andorra</label>
<input type="checkbox" name="..." value="AE" /><label for="...">United Arab Emirates</label>
<input type="checkbox" name="..." value="AF" /><label for="...">Afghanistan</label>
I would like each option displayed on it's own line in the browser, instead of all in a row. How can I inject html around or between the options? Or is there a CSS method to accomplish this?
Thanks.
From The Symfony Docs
What you basically need to do is to overload checkbox_widget block.
{% form_theme form _self %}
{% block checkbox_widget %}
{% spaceless %}
<input type="checkbox" {{ block('widget_attributes') }}{% if value is defined %} value="{{ value }}"{% endif %}{% if checked %} checked="checked"{% endif %} />
{% endspaceless %}
{% endblock checkbox_widget %}
Of course you can place your widgets in its own line with CSS (but it's not a Symfony2 question).
A lazier way I found to do this was to iterate through the form/choice array.
At its simplest, rendering a form you might do:
{{ form_widget(form) }}
For a little more granularity, you might do:
{{ form_row(form.itemA) }}
{{ form_row(form.itemB) }}
{{ form_row(form.itemC) }}
But if "itemA" is a multi-choice, you're stuck with the entire list getting rendered on the same line. If you're looking for just a little more granularity before you step up to theming, you can do this:
{% for t in form.itemA %}
{{ form_row(t) }}
{% endfor %}
That'll render each checkbox on its own line, or give you an opportunity to do whatever you want between each item.
As Kuba has said in his answer this sounds partly like a CSS question. Semantically speaking injecting something like a <br />
tag doesn't have much meaning but you can do that if you wish by following the documents in Kuba's answer.
If you wish to write some CSS to get those elements to display line by line you can use this against symfony's default output:
input, label {
float: left;
}
input {
clear: left;
}
Of course this will actually cause all input and label tags to float left which might not be suitable to you so you can a) wrap your checkboxes in another div and use a css sub-selector like .checkboxes input, .checkboxes label
or b) apply a custom css class to your widgets using:
{{ form_widget(form.name, { 'attr': {'class': 'foo'} }) }}
and the CSS would be the same but instead of input
you'd have .foo
.
来源:https://stackoverflow.com/questions/8568515/symfony2-how-to-render-checkboxes