Symfony2: dynamic inline form generation

Symfony2 is able to creates dynamic generation .

However, there is a big problem with the dynamic generation of inline forms based on user submitted data:

If I use FormEvents :: PRE_SET_DATA, then I can not get post data for the inline form - only the data of the parent objects is available

$builder->get('contacts')->addEventListener( FormEvents::POST_SET_DATA function(FormEvent $event) { $data = $event->getData(); //$data will contain embedded form object - not the data object! } ); 

If I use FormEvents :: POST_SUBMIT, then I can receive the data, but I can not change the form

 $builder->get('contacts')->addEventListener( FormEvents::POST_SUBMIT, function(FormEvent $event) { $data = $event->getData(); //$data will contain filled data object - everything is ok $form = $event->getForm(); //form will be ok if ($data->getSomeValue()) { $form->add(...); //Error: "You cannot add children to a submitted form" } } ); 

Please help: is there a way to dynamically generate an inline form based on user submitted data?

I am using Symfony 2.4.

Thank you in advance!

+6
source share
1 answer

The problem was easily resolved: you must use the events FormEvents :: SUBMIT or FormEvents :: PRE_SUBMIT.

For both of them, you can get the sending data and change the form.

The difference between them:

  • FormEvents :: PRE_SUBMIT - the data is not normalized, therefore $ event-> getData () returns a simple array
  • FormEvents :: SUBMIT - the data is NORMALIZED, therefore returns $ event-> getData () object of the model

And there is an even better opportunity:

You can use FormEvents :: POST_SUBMIT, but you need to attach it to the subform field, and not to the entire subform.

In this case, you can:

  • Get all POST data in normalized form (model object)
  • Change the form fields that come after which event is associated.
  • Field values ​​will be automatically set based on POST data.
+9
source

All Articles