0
votes

I'm trying show some form fields only when creating new entry. I do that using this article in symfony cookbook. The problem is, that fields added by EventListener goes to bottom of form (my real form contains more fields). So I get field2, field3, field1. How could I move this field to the top by not modifying templates?

 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
It's not available in Symfony (as far as I know) but there is a bundle for it - github.com/egeloen/IvoryOrderedFormBundle - qooplmao

2 Answers

1
votes

Just reserve position for this field in form builder using for example hidden input. Event listener will overwrite this field.

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

As Qoop mentioned, there is no such functionality in Symfony, but there is a bundle for it.

Simple solution using this bundle:

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

There is much more ordering functionality, check bundles's documentation.