[Form] refactor `RadioListMapper::mapDataToForm()`

This fixes "false" choice pre selection when `ChoiceType`
is `expanded` and not `multiple`
This commit is contained in:
Jules Pietri 2016-02-19 15:39:54 +01:00
parent 3eac4693ad
commit 8f918e5f84
2 changed files with 10 additions and 4 deletions

View File

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

View File

@ -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']) {
// <select> tag with "multiple" option