Skip to content

Commit a7e1e84

Browse files
author
Cristoforo Cervino
committed
fix fatal error when using an object as default value in ChoiceType
1 parent a9ad35e commit a7e1e84

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

src/Bridge/Transformer/ChoiceTransformer.php

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
use Matthias\SymfonyConsoleForm\Console\Helper\Question\AlwaysReturnKeyOfChoiceQuestion;
66
use Symfony\Component\Console\Question\Question;
7+
use Symfony\Component\Form\ChoiceList\View\ChoiceView;
78
use Symfony\Component\Form\FormInterface;
89

910
final class ChoiceTransformer extends AbstractTransformer
@@ -20,4 +21,21 @@ public function transform(FormInterface $form): Question
2021

2122
return $question;
2223
}
24+
25+
protected function defaultValueFrom(FormInterface $form)
26+
{
27+
$defaultValue = parent::defaultValueFrom($form);
28+
29+
// $defaultValue could be an object
30+
// Let's find out what form computed to be its view representation
31+
$formView = $form->createView();
32+
$defaultValueFromChoiceView = \array_reduce(
33+
$formView->vars['choices'],
34+
static fn(
35+
?string $carry,
36+
ChoiceView $choiceView
37+
): ?string => (null === $carry && $choiceView->data === $defaultValue) ? $choiceView->value : $carry
38+
);
39+
return $defaultValueFromChoiceView ?? $defaultValue;
40+
}
2341
}

0 commit comments

Comments
 (0)