dreamice2013 2015-01-13 15:20
浏览 48

Symfony 2.6 - 按名称呈现个人选择字段(收音机,复选框)

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
            ));
    }

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?

I tried offsetGet (which is supposed to return a child by name), but it also works only with array index.

  • 写回答

4条回答 默认 最新

  • doujin4031 2015-08-25 11:43
    关注

    It appears this is not possible with the latest versions of Symfony (i.e. >= 2.6). I recall in previous versions, when the form builder displayed the choices array, it was generating the choices like this:

    <select>
        <option value="road">Car/Bus</option>
        <option value="train">Train</option>
    </select>
    

    This, however, has been changed in the recent versions to the following:

    <select>
        <option value="0">Car/Bus</option>
        <option value="1">Train</option>
    </select>
    

    The selected option is then normalized and then you get the expected value you've set in the FormType class. You can read more about normalization here.

    Also, If you write {{ debug(form.transport) }} in Symfony >= 2.6, you can see the form/field array and what you can use from it.

    评论

报告相同问题?

悬赏问题

  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算