'Symfony: Custom Form Type throws "This value is not valid" error despite having the correct value type
I am creating a web app via Symfony and EasyAdmin. Within a form, I created a custom form field to render an integer. The integer is a mapped value of the form entity.
The form field:
$laufzeit = MonateChoiceField::new('laufzeitMonate');
The custom form type:
$builder
->add('laufzeit_choice', ChoiceType::class, [
'choices' => [
'24 Monate' => 24,
'36 Monate' => 36,
'60 Monate' => 60,
'Unbefristet' => -1,
'Eigene Eingabe' => -2,
],
'label' => 'Laufzeit in Monaten'
])
->add('laufzeit_custom', IntegerType::class, [
'attr' => [
'class' => 'form-control ',
'min' => '0',
],
'invalid_message' => 'custom',
'label' => 'Benutzerdefinierte Laufzeit in Monaten',
])
;
Basically, I want my value to load into the ChoiceType if it is within the given choices, and into the IntegerType if it isn't.
My event listener for PRE_SET works perfectly fine:
$data = $event->getData();
$choiceData = -2;
switch ($data) {
case 24:
case 36:
case 60:
case -1:
$choiceData = $data;
break;
default:
break;
}
$dataNew = [
"laufzeit_choice" => $choiceData,
"laufzeit_custom" => $data,
];
$event->setData($dataNew);
However, when trying to save the form, I get the error message "This value is not valid." with no further details. My PRE_SUBMIT looks as follows:
$data = $event->getData();
$dataNew = intval($data['laufzeit_choice']);
if($data['laufzeit_choice'] == -2) {
$dataNew = intval($data['laufzeit_custom']);
}
$event->setData($dataNew);
So my submitted data is an integer, either the value of the ChoiceType or the IntegerType. So in theory the form gets the correct format.
What am I missing?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
