New in Symfony 8.2 (in development). A form can handle JSON: $form->submit($request->toArray()). But a field that is neither compound nor multiple, like a TextType, rejected an array before the PRE_SUBMIT event. There was no way to transform it in a listener: PRE_SUBMIT wasn't even dispatched on the field, which showed "This value is not valid.".
allow_array_submission
The new option runs the listeners first:
$builder->add('tags', TextType::class, [ 'allow_array_submission' => true, ]); $builder->get('tags')->addEventListener(FormEvents::PRE_SUBMIT, function (PreSubmitEvent $event): void { if (\is_array($tags = $event->getData())) { $event->setData(implode(',', $tags)); } }, 10);
- Give the listener a priority above 0: it then runs before the listeners of the field type, which get the value already transformed.
- If the data is still an array after the listeners, the form fails with the same error as before.
- The option is
falseby default: once it is on, everyPRE_SUBMITlistener of the field must cope with an array.
Your task
The article editor sends the tags as a JSON array (["symfony", "php"]), but the draft keeps them as one comma-separated string, with no spaces (symfony,php). Right now, the API responds with a 422 as soon as an array comes in.
- Allow the array on the
tagsfield. - Add a
PRE_SUBMITlistener, with a priority above 0, that turns the array into a string. A string must still be accepted.
Try the exercise's two requests before and after.