Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2: dynamic generation of embedded form

Symfony2 has possibility of forms dynamic generation.

However there is big problem with dynamic generation of embedded forms based on user submitted data:

If I use FormEvents::PRE_SET_DATA then I can't receive post data for embedded form - only parent object data 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 may receive data but I can't modify 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 any way to dynamically generate embedded form based on user submitted data?

I use Symfony 2.4.

Thank you very much in advance!

like image 469
Yuri Shanoylo Avatar asked Feb 11 '14 15:02

Yuri Shanoylo


1 Answers

The problem was easy to solve: it is needed to use FormEvents::SUBMIT or FormEvents::PRE_SUBMIT events.

For both of them it is possible to get submit data and to change the form.

The difference between them:

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

And there is even better possibility:

You may use FormEvents::POST_SUBMIT BUT you need to attach it to the subform field - not to the whole subform.

In such case you'll be able to:

  1. Get all POST data in normalized form (model object)
  2. Modify form fields which goes after one to which event is bound
  3. Fields values we'll be automatically set based on POST data
like image 83
Yuri Shanoylo Avatar answered Sep 30 '22 01:09

Yuri Shanoylo