1
votes

I'm facing a problem with Symfony 3.4 :

I have a formbuilder including 2 buttons ('add' and 'extract') and when 'add' is clicked, I want to add a new field in a CollectionType instead of doing the "extract" stuff.

I tried to do it with FormEvent but when I can tell which button isClicked() (SUBMIT), it's too late to call $event->setData() and $event->getForm()->setData() do nothing. On the other hand, when I can setData() (PRE_SUBMIT), I can't tell which button isClicked() since the information isn't computed yet in the submission process.

How can I achieve to add a value in my CollectionType (and so, a new field) after the 'add' button be clicked.

Thanks

$this->createFormBuilder(array('columns' => array(1, 2, 3)))
            ->add('columns', CollectionType::class, array(
                'entry_type' => TextType::class
            ))
            ->add('extract', SubmitType::class)
            ->add('add', SubmitType::class)
            ->addEventListener(FormEvents::SUBMIT, function(FormEvent $event) {

                if ($event->getForm()->get('add')->isClicked()) {

                    $data = $event->getData();
                    $data['columns'][] = null;
                    $event->setData($data);
                }
            })
            ->getForm()
            ->handleRequest($request)
2

2 Answers

1
votes

You cannot add or remove fields on the SUBMIT event. It's too late. You need to do it in the PRE_SUBMIT (cf: https://symfony.com/doc/current/form/events.html#b-the-formevents-submit-event)

Try to check if the 'add' key is present in $data instead of checking for isClicked():

->addEventListener(FormEvents::PRE_SUBMIT, function(FormEvent $event) {
        $data = $event->getData();
        if (isset($data['add'])) {
              $data['columns'][] = null;
              $event->setData($data);
        } 
})
1
votes

@Youri_G is mostly correct, but setData has to be called by a defined form-field instead of a FormEvent so that symfony knows which field should be modified:

$form = $this->createFormBuilder(array('columns' => array(1, 2, 3)))
        ->add('columns', CollectionType::class, array(
            'entry_type' => TextType::class
        ))
        ->add('extract', SubmitType::class)
        ->add('add', SubmitType::class)
        ->addEventListener(FormEvents::PRE_SUBMIT, function(FormEvent $event) {

            $data = $event->getData();

            if (isset($data["add"])) {

                $data['columns'][] = null;
                // in this way the symfony knows which field should be modified
                $event->getForm()->get("columns")->setData($data['columns']);

            }
        })
        ->getForm();

$form->handleRequest($request);