8000 [Form] refactor `RadioListMapper::mapDataToForm()` · symfony/symfony@8f918e5 · GitHub
[go: up one dir, main page]

Skip to content

Commit 8f918e5

Browse files
committed
[Form] refactor RadioListMapper::mapDataToForm()
This fixes "false" choice pre selection when `ChoiceType` is `expanded` and not `multiple`
1 parent 3eac469 commit 8f918e5

File tree

2 files changed

+10
-4
lines changed

2 files changed

+10
-4
lines changed

src/Symfony/Component/Form/Extension/Core/DataMapper/RadioListMapper.php

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -38,13 +38,11 @@ public function __construct(ChoiceListInterface $choiceList)
3838
/**
3939
* {@inheritdoc}
4040
*/
41-
public function mapDataToForms($choice, $radios)
41+
public function mapDataToForms($data, $radios)
4242
{
43-
$valueMap = array_flip($this->choiceList->getValuesForChoices(array($choice)));
44-
4543
foreach ($radios as $radio) {
4644
$value = $radio->getConfig()->getOption('value');
47-
$radio->setData(isset($valueMap[$value]) ? true : false);
45+
$radio->setData($value === $data ? true : false);
4846
}
4947
}
5048

src/Symfony/Component/Form/Extension/Core/Type/ChoiceType.php

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,14 @@ public function buildForm(FormBuilderInterface $builder, array $options)
143143
$event->setData(null);
144144
}
145145
});
146+
// For radio lists, pre selection of the choice needs to pre set data
147+
// with the string value so it can be matched in
148+
// {@link \Symfony\Component\Form\Extension\Core\DataMapper\RadioListMapper::mapDataToForms()}
149+
$builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
150+
$choiceList = $event->getForm()->getConfig()->getOption('choice_list');
151+
$value = current($choiceList->getValuesForChoices(array($event->getData())));
152+
$event->setData((string) $value);
153+
});
146154
}
147155
} elseif ($options['multiple']) {
148156
// <select> tag with "multiple" option

0 commit comments

Comments
 (0)
0