Symfony: SUBMIT ad POST_SUBMIT form events: change the data of a submitted form.

Created on 5 Dec 2016  路  1Comment  路  Source: symfony/symfony

Hi,

it is said at Form Events docs that inside SUBMIT and POST_SUBMIT event listeners:

You cannot add or remove fields to the form.

so when I have this code:

->addEventListener(FormEvents::SUBMIT, function (FormEvent $event) use ($em) { 
        $form = $event->getForm();

        $repository = $em->getRepository('ZiiwebPurchaseBundle:Tag');

        $tag = $repository->find(array('id' => 2));
        $form->add('tag', EntityType::class, array('class' => 'ZiiwebPurchaseBundle:Tag'));

        $data = $form->getData();
    $data->setTag($tag);
        $form->setData($data);

I get this error: You cannot change the data of a submitted form..

but I can do this without any warning or error:

->addEventListener(FormEvents::SUBMIT, function (FormEvent $event) use ($em) { 
        $form = $event->getForm();

        $repository = $em->getRepository('ZiiwebPurchaseBundle:Tag');

        $tag = $repository->find(array('id' => 2));
        $form->add('tag', EntityType::class, array('class' => 'ZiiwebPurchaseBundle:Tag'));

        $form->getData()->setTag($tag); //<<<<<<<<< here I'm chaging the submitted form

Is this a bug or it is kind of allowed to change the submitted data that way?

Bug Form Needs Review Unconfirmed

Most helpful comment

Hi @Ziiweb. This is an expected behavior.

In fact you can add/remove fields on every events but this does not make sense in POST_SUBMIT.

However regarding data:

$eventData = $event->getData();
$formData = $event->getForm()->getData();

// PRE_SUBMIT
$eventData !== $formData
// (array from request) !== (model pre set data)

// SUBMIT
$eventData !== $formData
// (normalized data after view reverse transform) !== (model pre set data)

// POST_SUBMIT
$eventData === $formData
// (model data hydrated after submission in both case)

In any case (excepted POST_SUBMIT), in you want to modify data, you should never call $form->setData() as this is handled internally.

But you can use $event->setData() instead.

This issue can be closed then, I hope it helps you!

>All comments

Hi @Ziiweb. This is an expected behavior.

In fact you can add/remove fields on every events but this does not make sense in POST_SUBMIT.

However regarding data:

$eventData = $event->getData();
$formData = $event->getForm()->getData();

// PRE_SUBMIT
$eventData !== $formData
// (array from request) !== (model pre set data)

// SUBMIT
$eventData !== $formData
// (normalized data after view reverse transform) !== (model pre set data)

// POST_SUBMIT
$eventData === $formData
// (model data hydrated after submission in both case)

In any case (excepted POST_SUBMIT), in you want to modify data, you should never call $form->setData() as this is handled internally.

But you can use $event->setData() instead.

This issue can be closed then, I hope it helps you!

Was this page helpful?
0 / 5 - 0 ratings