Symfony 2.6 - 按名称呈现单个选择字段(单选框、复选框)
如何在 Symfony 2.6 的 Twig 中呈现单个字段(单个单选框/复选框输入字段)?
How can I render an individual field (single radio/checkbox input field) in Twig in Symfony 2.6?
假设我有一个简单的表格:
Let's say I have a simple form:
class TransportType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('transport', 'choice', array(
'choices' => array(
'road' => 'Car/bus',
'train' => 'Train',
),
'expanded' => true,
'multiple' => false
));
}
在以前的 Symfony2 版本中我可以使用:
In previous Symfony2 versions I could just use:
{{ form_widget(form.transport.road) }}
{{ form_widget(form.transport.train) }}
渲染单个单选按钮,但它似乎不再起作用.我知道我可以使用:
to render individual radio buttons, but it doesn't seem to work anymore. I know I can use:
{{ form_widget(form.transport[0]) }}
{{ form_widget(form.transport[1]) }}
但它不太灵活.当然,我可以遍历集合并检查名称,但这似乎是不必要的麻烦.没有更简单的方法吗?
but it's less flexible. Of course I can iterate over the collection and check for name, but this seems like unnecessary hassle. Isn't there an easier way?
我尝试了offsetGet
(它应该按名称返回一个孩子
),但它也只适用于数组索引.
I tried offsetGet
(which is supposed to return a child by name
), but it also works only with array index.
推荐答案
试试这个:
{% for key, transportItem in form.transport.children %}
{{ form_widget(transportItem) }}
{% endfor %}
相关文章