Symfony 8.2 New Published on

A JSON array in a text field, with allow_array_submission

A text field receiving a JSON array was rejected before any listener. allow_array_submission lets PRE_SUBMIT transform it first.

Topics covered: FormsAPI

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 false by default: once it is on, every PRE_SUBMIT listener 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.

  1. Allow the array on the tags field.
  2. Add a PRE_SUBMIT listener, 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.

Where the feature comes from: the original pull request.