8

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!

1 Answer 1

10

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
Sign up to request clarification or add additional context in comments.

1 Comment

I'm struggling to get normalized data from FormEvents::SUBMIT and can't modify form fields in FormEvents::POST_SUBMIT – even when binding to the subform field and no matter what order fields are in.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.