Rolintocour
Rolintocour

Reputation: 3158

Symfony2: get post data from PRE_SET_DATA event

I have a form with bound selects, i.a. changing select 1 may update select 2 that may update select 3 and so one.

In order to to give the right "choices" to my selects (only a few should be displayed at loading, another after changing the select. After a POST, the correct choices should also be set), I set an event listener on the PRE_SET_DATA event.

In this listener, I have:

$updatetodate_object = $event->getData();
$form = $event->getForm();

The problem is that my $updatetodate_object isn't up to date, there are still the values from DB and not the user's data, after a POST, whereas I need the updated value to build the "choices".

I also tried:

$form->getData()

which returns me an exception:

A cycle was detected. Listeners to the PRE_SET_DATA event must not call setData(). 
You should call setData() on the FormEvent object instead. 

Any idea?

Upvotes: 3

Views: 6194

Answers (2)

Rolintocour
Rolintocour

Reputation: 3158

Finally I use the PRE_SUBMIT event. It gives me an array of values instead of the formed object but it is OK. A strange thing is that using the SUBMIT event, it returns an object but the sub-forms are returned before the main object, which is annoying for me.

Upvotes: 1

kba
kba

Reputation: 4310

It is expected behaviour according to http://symfony.com/doc/current/cookbook/form/dynamic_form_modification.html#dynamic-generation-for-submitted-forms

However, things get more difficult when you handle the form submission. This is because the PRE_SET_DATA event tells us the data that you're starting with (e.g. an empty SportMeetup object), not the submitted data.

You should try another event. PRE_SUBMIT is first where you can get submitted data.

http://symfony.com/doc/current/components/form/form_events.html#submitting-a-form-formevents-pre-submit-formevents-submit-and-formevents-post-submit

Upvotes: 4

Related Questions