symfony: ChoiceType returns wrong data on submit if clearMissing is false

I’ve created TestFormType

class TestType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('text', 'text')
            ->add('choice', 'choice', ['choices' => ['FOO' => 'foo', 'BAR' => 'bar'], 'expanded' => true])
        ;
    }

    public function getName()
    {
        return 'test';
    }
}

created the form and trying to submit data

$data = [
    'text'   => 'foo',
    'choice' => 'foo',
];
$form = $this->createForm('test', $data);
$form->submit(
    [
        'text'   => 'bar',
        'choice' => 'bar',
    ],
    false
);

and now $form->getData() will return an array:

array (size=2)
    'text' => string 'bar' (length=3)
    'choice' => string 'foo' (length=3)

I expect to receive bar for both fields.

I’m working on the latest version of 4.4 branch See the reproducer for this issue https://github.com/ossinkine/symfony-issue-16802

About this issue

  • Original URL
  • State: closed
  • Created 9 years ago
  • Comments: 30 (28 by maintainers)

Commits related to this issue

Most upvoted comments

Thank you @xabbuh, your fix fixes the issue for me

We have run into this issue today as well on symfony 5.1.3. We found that a form eventlistener helped us work around the issue:

<?php

namespace App\Form\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\Event\PreSubmitEvent;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;

class ChoiceSubscriber implements EventSubscriberInterface
{
    /**
     * {@inheritdoc}
     */
    public static function getSubscribedEvents()
    {
        return [
            FormEvents::PRE_SUBMIT => 'onPreSubmit',
        ];
    }

    /**
     * @param PreSubmitEvent $event
     * @throws \Symfony\Component\Form\Exception\OutOfBoundsException
     * @throws \Symfony\Component\Form\Exception\RuntimeException
     * @throws \Symfony\Component\Form\Exception\TransformationFailedException
     */
    public function onPreSubmit(PreSubmitEvent $event)
    {
        $form = $event->getForm();
        $data = $event->getData();

        if (isset($data['choice']) && $data['choice'] !== $form->get('choice')->getData()) {
            $form->get('choice')->setData(null);
        }
    }
}

The work around constitutes checking during the pre submit event if the submitted data has changed compared to the pre-populated form data. If this is the case reset the current form data to null. Hopefully this helps others who might run into this problem in the future until a patch is made to fix it.