diff --git a/src/Symfony/Component/Form/ChoiceList/Factory/DefaultChoiceListFactory.php b/src/Symfony/Component/Form/ChoiceList/Factory/DefaultChoiceListFactory.php index 68da1b2516..338877e05e 100644 --- a/src/Symfony/Component/Form/ChoiceList/Factory/DefaultChoiceListFactory.php +++ b/src/Symfony/Component/Form/ChoiceList/Factory/DefaultChoiceListFactory.php @@ -101,6 +101,14 @@ class DefaultChoiceListFactory implements ChoiceListFactoryInterface unset($otherViews[$key]); } } + + foreach ($preferredViewsOrder as $key => $groupViewsOrder) { + if ($groupViewsOrder) { + $preferredViewsOrder[$key] = min($groupViewsOrder); + } else { + unset($preferredViewsOrder[$key]); + } + } } else { // Otherwise use the original structure of the choices self::addChoiceViewsFromStructuredValues( @@ -245,6 +253,9 @@ class DefaultChoiceListFactory implements ChoiceListFactoryInterface $preferredViews[$groupLabel] = new ChoiceGroupView($groupLabel); $otherViews[$groupLabel] = new ChoiceGroupView($groupLabel); } + if (!isset($preferredViewsOrder[$groupLabel])) { + $preferredViewsOrder[$groupLabel] = []; + } self::addChoiceView( $choice, @@ -255,7 +266,7 @@ class DefaultChoiceListFactory implements ChoiceListFactoryInterface $attr, $isPreferred, $preferredViews[$groupLabel]->choices, - $preferredViewsOrder, + $preferredViewsOrder[$groupLabel], $otherViews[$groupLabel]->choices ); } diff --git a/src/Symfony/Component/Form/Tests/ChoiceList/Factory/DefaultChoiceListFactoryTest.php b/src/Symfony/Component/Form/Tests/ChoiceList/Factory/DefaultChoiceListFactoryTest.php index 6282007195..3074f0f160 100644 --- a/src/Symfony/Component/Form/Tests/ChoiceList/Factory/DefaultChoiceListFactoryTest.php +++ b/src/Symfony/Component/Form/Tests/ChoiceList/Factory/DefaultChoiceListFactoryTest.php @@ -256,6 +256,37 @@ class DefaultChoiceListFactoryTest extends TestCase ); } + public function testCreateViewFlatPreferredChoiceGroupsSameOrder() + { + $view = $this->factory->createView( + $this->list, + [$this->obj4, $this->obj2, $this->obj1, $this->obj3], + null, // label + null, // index + [$this, 'getGroup'] + ); + + $preferredLabels = array_map(static function (ChoiceGroupView $groupView): array { + return array_map(static function (ChoiceView $view): string { + return $view->label; + }, $groupView->choices); + }, $view->preferredChoices); + + $this->assertEquals( + [ + 'Group 2' => [ + 2 => 'C', + 3 => 'D', + ], + 'Group 1' => [ + 0 => 'A', + 1 => 'B', + ], + ], + $preferredLabels + ); + } + public function testCreateViewFlatPreferredChoicesEmptyArray() { $view = $this->factory->createView(