Skip to content

Commit

Permalink
bug #6201 [ChoiceField] Bugfix: Enum translation for Grid (psihius)
Browse files Browse the repository at this point in the history
This PR was squashed before being merged into the 4.x branch.

Discussion
----------

[ChoiceField] Bugfix: Enum translation for Grid

The translation array is based on the enum's `name` field, so when choosing translation for the grid, it should also select `name` instead of `value` as the selected value.
This is important when Enum's name and value do not match, like in integer-based enum's or when the case name is not the same as it's value.
Also replaced the array_merge with a foreach that adds data to the array instead of fully rebuilding a new copy of the array with new data.

Commits
-------

178ecc7 [ChoiceField] Bugfix: Enum translation for Grid
  • Loading branch information
javiereguiluz committed Mar 14, 2024
2 parents 4127bf2 + 178ecc7 commit 8f20bcd
Showing 1 changed file with 7 additions and 2 deletions.
9 changes: 7 additions & 2 deletions src/Field/Configurator/ChoiceConfigurator.php
Expand Up @@ -33,6 +33,8 @@ public function configure(FieldDto $field, EntityDto $entityDto, AdminContext $c
$choicesSupportTranslatableInterface = false;
$isExpanded = true === $field->getCustomOption(ChoiceField::OPTION_RENDER_EXPANDED);
$isMultipleChoice = true === $field->getCustomOption(ChoiceField::OPTION_ALLOW_MULTIPLE_CHOICES);
// Initialize the variable since we are using it outside the $enumsAreSupported condition
$allChoicesAreEnums = false;

$choices = $this->getChoices($field->getCustomOption(ChoiceField::OPTION_CHOICES), $entityDto, $field);

Expand Down Expand Up @@ -132,7 +134,8 @@ public function configure(FieldDto $field, EntityDto $entityDto, AdminContext $c
$flippedChoices = $areChoicesTranslatable ? $choices : array_flip($this->flatten($choices));
foreach ((array) $fieldValue as $selectedValue) {
$selectedValue = match (true) {
$selectedValue instanceof \BackedEnum => $selectedValue->value,
// We check if $allChoicesAreEnums is true for enum's and choices array is generated using ->name as index
$selectedValue instanceof \BackedEnum => $allChoicesAreEnums && $choicesSupportTranslatableInterface ? $selectedValue->name : $selectedValue->value,
$selectedValue instanceof \UnitEnum => $selectedValue->name,
default => $selectedValue
};
Expand Down Expand Up @@ -198,7 +201,9 @@ private function flatten(array $choices): array
foreach ($choices as $label => $choice) {
// Flatten grouped choices
if (\is_array($choice)) {
$flattened = array_merge($flattened, $choice);
foreach ($choice as $subLabel => $subChoice) {
$flattened[$subLabel] = $subChoice;
}
} elseif ($choice instanceof \BackedEnum) {
$flattened[$choice->name] = $choice->value;
} elseif ($choice instanceof \UnitEnum) {
Expand Down

0 comments on commit 8f20bcd

Please sign in to comment.