Skip to content

Commit f5bd76c

Browse files
vilius-gnicolas-grekas
authored andcommitted
[Form] Keep preferred_choices order for choice groups
1 parent 1134c09 commit f5bd76c

File tree

2 files changed

+43
-1
lines changed

2 files changed

+43
-1
lines changed

ChoiceList/Factory/DefaultChoiceListFactory.php

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,14 @@ public function createView(ChoiceListInterface $list, $preferredChoices = null,
101101
unset($otherViews[$key]);
102102
}
103103
}
104+
105+
foreach ($preferredViewsOrder as $key => $groupViewsOrder) {
106+
if ($groupViewsOrder) {
107+
$preferredViewsOrder[$key] = min($groupViewsOrder);
108+
} else {
109+
unset($preferredViewsOrder[$key]);
110+
}
111+
}
104112
} else {
105113
// Otherwise use the original structure of the choices
106114
self::addChoiceViewsFromStructuredValues(
@@ -245,6 +253,9 @@ private static function addChoiceViewsGroupedByCallable($groupBy, $choice, $valu
245253
$preferredViews[$groupLabel] = new ChoiceGroupView($groupLabel);
246254
$otherViews[$groupLabel] = new ChoiceGroupView($groupLabel);
247255
}
256+
if (!isset($preferredViewsOrder[$groupLabel])) {
257+
$preferredViewsOrder[$groupLabel] = [];
258+
}
248259

249260
self::addChoiceView(
250261
$choice,
@@ -255,7 +266,7 @@ private static function addChoiceViewsGroupedByCallable($groupBy, $choice, $valu
255266
$attr,
256267
$isPreferred,
257268
$preferredViews[$groupLabel]->choices,
258-
$preferredViewsOrder,
269+
$preferredViewsOrder[$groupLabel],
259270
$otherViews[$groupLabel]->choices
260271
);
261272
}

Tests/ChoiceList/Factory/DefaultChoiceListFactoryTest.php

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -256,6 +256,37 @@ public function testCreateViewFlatPreferredChoicesSameOrder()
256256
);
257257
}
258258

259+
public function testCreateViewFlatPreferredChoiceGroupsSameOrder()
260+
{
261+
$view = $this->factory->createView(
262+
$this->list,
263+
[$this->obj4, $this->obj2, $this->obj1, $this->obj3],
264+
null, // label
265+
null, // index
266+
[$this, 'getGroup']
267+
);
268+
269+
$preferredLabels = array_map(static function (ChoiceGroupView $groupView): array {
270+
return array_map(static function (ChoiceView $view): string {
271+
return $view->label;
272+
}, $groupView->choices);
273+
}, $view->preferredChoices);
274+
275+
$this->assertEquals(
276+
[
277+
'Group 2' => [
278+
2 => 'C',
279+
3 => 'D',
280+
],
281+
'Group 1' => [
282+
0 => 'A',
283+
1 => 'B',
284+
],
285+
],
286+
$preferredLabels
287+
);
288+
}
289+
259290
public function testCreateViewFlatPreferredChoicesEmptyArray()
260291
{
261292
$view = $this->factory->createView(

0 commit comments

Comments
 (0)