bug #34083 [Form] Keep preferred_choices order for choice groups (vilius-g)

This PR was squashed before being merged into the 4.3 branch.

Discussion
----------

[Form] Keep preferred_choices order for choice groups

| Q             | A
| ------------- | ---
| Branch?       | 4.3
| Bug fix?      | yes
| New feature?  | no
| Deprecations? | no
| Tickets       |
| License       | MIT
| Doc PR        |

Since 4.3 ordering of `preferred_choices` is preserved when displaying form. But this only works for flat options. When the choices are grouped, the preferred groups are in default order.

Now the preferred choice group order is derived by taking the first matching choice from `preferred_choices` and using its position to sort the groups.

Commits
-------

75404e5287 [Form] Keep preferred_choices order for choice groups
This commit is contained in:
Nicolas Grekas 2019-11-28 12:24:09 +01:00
commit ab5e7fa706
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(