最好的方法是渲染一个ChoiceType
作为单选按钮:
->add(
'vacancyCurrency',
ChoiceType::class,
[
'choices' => [
'US Dolar' => 'usd',
'Euro' => 'eur',
],
'expanded' => true
]
);
当您有选项时,ChoiceType 字段会呈现为单选按钮multiple = false
and expanded = true
。选项multiple
上面的代码中没有,因为它的默认值是false
。您可以找到更多详细信息here https://symfony.com/doc/current/reference/forms/types/choice.html
Edit:
在你的树枝模板中,你只需要添加:
{{ form_widget(form.vacancyCurrency) }}
Edit 2
您在这个答案的评论中说过,您需要将每个单选按钮放在一个<div class="currency-label active">
。我相信你不能通过在 Symfony 表单字段本身中设置属性来做到这一点。您在那里拥有的选项,例如choice_attr
经营于input
,而不是在它周围的 div 中。
可以实现您想要的,但您需要编写一些代码并手动渲染单选按钮,例如:
<div class="form-group">
<label class="control-label required">Vacancy currency</label>
{% for child in form.vacancyCurrency %}
<div class="currency-label active">
<label for="{{ child.vars.id }}" class="required">
<input type="radio" id="{{ child.vars.id }}" name="{{ form.vars.id ~ '[' ~ form.vacancyCurrency.vars.name ~ ']' }}" required="required" class="checkbox" value="{{ child.vars.label }}">
{{ child.vars.label }}
</label>
</div>
{% endfor %}
</div>
当然,您可以使用一些 Javascript 来完成这项工作。例如,您可以呈现表单字段,如下所示:
{{ form_widget(form.vacancyCurrency) }}
它将在 div 中添加每个单选按钮class="radio"
.
然后,一旦页面准备好,您就可以使用一些 JQuery 将类更改为您想要的:
$(document).ready(function() {
$(".radio").attr("class", "currency-label active");
});