merged branch ericclemmons/2545-expanded-grouped-choices (PR #2731)

Commits
-------

7a8e1b3 ChoiceType flattens nested Choices when expanded
82b0b37 Added ChoiceType test for flattening grouped Choices when expanded

Discussion
----------

Fixed #2545 - ChoiceType flattens grouped Choices when expanded

Bug fix: yes
Feature addition: no
Backwards compatibility break: no
Symfony2 tests pass: yes
Fixes the following tickets: #2545

**Problem**: With PR #2464, a bug was discovered when nested choices threw a exception during rendering.

**Solution**: Nested choices are flattened prior to creating checkbox/radio fields.
This commit is contained in:
Fabien Potencier 2011-11-27 14:43:50 +01:00
commit 1f9cf94a1d
2 changed files with 42 additions and 1 deletions

View File

@ -41,7 +41,19 @@ class ChoiceType extends AbstractType
if ($options['expanded']) {
// Load choices already if expanded
$options['choices'] = $options['choice_list']->getChoices();
$choices = $options['choice_list']->getChoices();
// Flatten choices
$flattened = array();
foreach ($choices as $value => $choice) {
if (is_array($choice)) {
$flattened = array_replace($flattened, $choice);
} else {
$flattened[$value] = $choice;
}
}
$options['choices'] = $flattened;
foreach ($options['choices'] as $choice => $value) {
if ($options['multiple']) {

View File

@ -71,6 +71,35 @@ class ChoiceTypeTest extends TypeTestCase
));
}
public function testExpandedChoicesOptionsTurnIntoFields()
{
$form = $this->factory->create('choice', null, array(
'expanded' => true,
'choices' => $this->choices,
));
$this->assertEquals(count($this->choices), $form->count(), 'Each choice should become a new field');
}
public function testExpandedChoicesOptionsAreFlattened()
{
$form = $this->factory->create('choice', null, array(
'expanded' => true,
'choices' => $this->groupedChoices,
));
$flattened = array();
foreach ($this->groupedChoices as $choices) {
$flattened = array_replace($flattened, $choices);
}
$this->assertEquals(count($flattened), $form->count(), 'Each nested choice should become a new field, not the groups');
foreach ($flattened as $value => $choice) {
$this->assertTrue($form->has($value), 'Flattened choice is named after it\'s value');
}
}
public function testExpandedCheckboxesAreNeverRequired()
{
$form = $this->factory->create('choice', null, array(