From 8f918e5f84c53826d025cbb1f3a0bfe093acc4e0 Mon Sep 17 00:00:00 2001 From: Jules Pietri Date: Fri, 19 Feb 2016 15:39:54 +0100 Subject: [PATCH] [Form] refactor `RadioListMapper::mapDataToForm()` This fixes "false" choice pre selection when `ChoiceType` is `expanded` and not `multiple` --- .../Form/Extension/Core/DataMapper/RadioListMapper.php | 6 ++---- .../Component/Form/Extension/Core/Type/ChoiceType.php | 8 ++++++++ 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/src/Symfony/Component/Form/Extension/Core/DataMapper/RadioListMapper.php b/src/Symfony/Component/Form/Extension/Core/DataMapper/RadioListMapper.php index 19db183a28..d08a603b5c 100644 --- a/src/Symfony/Component/Form/Extension/Core/DataMapper/RadioListMapper.php +++ b/src/Symfony/Component/Form/Extension/Core/DataMapper/RadioListMapper.php @@ -38,13 +38,11 @@ class RadioListMapper implements DataMapperInterface /** * {@inheritdoc} */ - public function mapDataToForms($choice, $radios) + public function mapDataToForms($data, $radios) { - $valueMap = array_flip($this->choiceList->getValuesForChoices(array($choice))); - foreach ($radios as $radio) { $value = $radio->getConfig()->getOption('value'); - $radio->setData(isset($valueMap[$value]) ? true : false); + $radio->setData($value === $data ? true : false); } } diff --git a/src/Symfony/Component/Form/Extension/Core/Type/ChoiceType.php b/src/Symfony/Component/Form/Extension/Core/Type/ChoiceType.php index 58832ab2f8..ffabf8db46 100644 --- a/src/Symfony/Component/Form/Extension/Core/Type/ChoiceType.php +++ b/src/Symfony/Component/Form/Extension/Core/Type/ChoiceType.php @@ -143,6 +143,14 @@ class ChoiceType extends AbstractType $event->setData(null); } }); + // For radio lists, pre selection of the choice needs to pre set data + // with the string value so it can be matched in + // {@link \Symfony\Component\Form\Extension\Core\DataMapper\RadioListMapper::mapDataToForms()} + $builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) { + $choiceList = $event->getForm()->getConfig()->getOption('choice_list'); + $value = current($choiceList->getValuesForChoices(array($event->getData()))); + $event->setData((string) $value); + }); } } elseif ($options['multiple']) { //