[Form] Keep preferred_choices order for choice groups

This commit is contained in:
Vilius Grigaliūnas 2019-10-23 15:11:19 +03:00 committed by Nicolas Grekas
parent ddf9e0fa1c
commit 75404e5287
2 changed files with 43 additions and 1 deletions

View File

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

View File

@ -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(