在我的表单中,我有一些复选框, 但默认情况下,我有:
- 第一个 radio 小部件
- 第一个标签
- 第二个单选小部件
- 标签
这是 SYmfony2 生成的 html 代码:
<div>
<input ...>
<label ...></label>
<input ...>
<label ...></label>
</div>
我想要的是:
第一个单选小部件第一个标签
第二个单选小部件第二个标签
html 代码为:
<label .....><input ....></label>
我想我必须覆盖 choice_widget 但不知道如何将输入和标签放在同一行
这是我可能需要覆盖的 choice_widget :
{% block choice_widget %}
{% spaceless %}
{% if expanded %}
<div {{ block('widget_container_attributes') }}>
{% for child in form %}
{{ form_widget(child) }} {{ form_label(child) }}
{% endfor %}
</div>
{% else %}
<select {{ block('widget_attributes') }}{% if multiple %} multiple="multiple"{% endif %}>
{% if empty_value is not none %}
<option value="">{{ empty_value|trans }}</option>
{% endif %}
{% if preferred_choices|length > 0 %}
{% set options = preferred_choices %}
{{ block('widget_choice_options') }}
{% if choices|length > 0 and separator is not none %}
<option disabled="disabled">{{ separator }}</option>
{% endif %}
{% endif %}
{% set options = choices %}
{{ block('widget_choice_options') }}
</select>
{% endif %}
{% endspaceless %}
{% endblock choice_widget %}
最佳答案
我遇到了同样的问题,找不到解决方案,所以我自己解决了。你是对的,你确实需要覆盖 {% block choice_widget %}
block 。第一步是从打印出单独标签的 {% if expanded %}
部分删除 {{ form_label(child) }}
行。
{% block choice_widget %}
{% spaceless %}
{% if expanded %}
<div {{ block('widget_container_attributes') }}>
{% for child in form %}
{{ form_widget(child) }}
{# {{ form_label(child) }} <--------------------- remove this line #}
{% endfor %}
</div>
{% else %}
<select {{ block('widget_attributes') }}{% if multiple %} multiple="multiple"{% endif %}>
{% if empty_value is not none %}
<option value="">{{ empty_value|trans }}</option>
{% endif %}
{% if preferred_choices|length > 0 %}
{% set options = preferred_choices %}
{{ block('widget_choice_options') }}
{% if choices|length > 0 and separator is not none %}
<option disabled="disabled">{{ separator }}</option>
{% endif %}
{% endif %}
{% set options = choices %}
{{ block('widget_choice_options') }}
</select>
{% endif %}
{% endspaceless %}
{% endblock choice_widget %}
现在您只需要处理打印 {% block checkbox_widget %}
block 中的标签。
{% block checkbox_widget %}
{% spaceless %}
<label for="{{ id }}"><input type="checkbox" {{ block('widget_attributes') }}{% if value is defined %} value="{{ value }}"{% endif %}{% if checked %} checked="checked"{% endif %} />{{ label|trans }}</label>
{% endspaceless %}
{% endblock checkbox_widget %}
您需要对 {% block radio_widget %}
执行相同的操作,否则它现在不会有标签。
{% block radio_widget %}
{% spaceless %}
<label for="{{ id }}"><input type="radio" {{ block('widget_attributes') }}{% if value is defined %} value="{{ value }}"{% endif %}{% if checked %} checked="checked"{% endif %} />{{ label|trans }}</label>
{% endspaceless %}
{% endblock radio_widget %}
关于php - Symfony2 - 如何将复选框/ radio 的标签和输入放在同一行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11507217/