Reputation: 1931
Starting from the example in the symfony cookbook about dynamic form generation (link to doc)
class SportMeetupType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('sport', 'entity', array(...))
;
$builder->addEventListener(
FormEvents::PRE_SET_DATA,
function(FormEvent $event) {
$form = $event->getForm();
// this would be your entity, i.e. SportMeetup
$data = $event->getData();
$positions = $data->getSport()->getAvailablePositions();
$form->add('position', 'entity', array('choices' => $positions));
}
);
}
}
I reproduced this code with a difference, I embed this form in a parent form (called for the exemple SportPlayerType
).
SportPlayerType
is mapped on entity SportPlayer
which contains a couple of attributes : $name and $meetup, a string and a SportMeetup.
My problem is in the lambda function, parameter of the addEventListener :
$event->getForm()
returns the child form SportMeetupType$event->getData()
returns the parent mapped entity SportPlayerAs a result, $form->add('position')
throw an error because the FormBuilder cannot match position
field on entity SportPlayer.
How could I force matching between SportMeetupType and entity SportMeetup when SportMeetupType in an embed form?
Upvotes: 0
Views: 1864
Reputation: 52483
We'll there is a reason the event is called PRE_SET_DATA
...
Namely the event gets fired before the submitted data is set.
Therefore you can't access ...
$event->getData()->getSport();
... in the listener as long as you don't provide a new Sport()
object or an existing entity when creating the form i.e. in a controller like this:
$entity = new Sport(); // ... or get the entity from db
$form = $this->createForm(new SportMeetupType(), $entity);
Just use the POST_SET_DATA
event and the data will be available.
Upvotes: 1