由EventListener添加的Symfony2 FormBuilder订单字段

时间:2014-08-21 10:40:25

标签: php forms symfony event-listener formbuilder

我只是在创建新条目时尝试显示某些表单字段。我在symfony cookbook中使用this article来做到这一点。问题是,EventListener添加的字段会转到表单的底部(我的真实表单包含更多字段)。所以我得到field2,field3,field1。如何通过不修改模板将此字段移到顶部?

 public function buildForm(FormBuilderInterface $builder, array $options)
 {
        $builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
            $task = $event->getData();
            $form = $event->getForm();

            //add just for new entity
            if (!$task || null === $task->getId()) {
                 $form->add('field1', null);
            }

        });     

        $builder->add('field2', null);
        $builder->add('field3', null);  
    }

2 个答案:

答案 0 :(得分:1)

只需使用隐藏输入在表单构建器中为此字段保留位置即可。事件监听器将覆盖此字段。

$builder->add('field1', 'hidden');
$builder->add('field2', null);
$builder->add('field3', null);

答案 1 :(得分:0)

正如Qoop所说,Symfony中没有这样的功能,但有一个bundle for it

使用此捆绑包的简单解决方案:

 public function buildForm(FormBuilderInterface $builder, array $options)
 {
        $builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
            $task = $event->getData();
            $form = $event->getForm();

            //add just for new entity
            if (!$task || null === $task->getId()) {
                 $form->add('field1', null, array('position' => 'first'));
            }

        });     

        $builder->add('field2', null);
        $builder->add('field3', null);  
 }

还有更多订购功能,请检查bundles's documentation