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 SportPlayer
As 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?
$form->get('sport'), assuming that it what this form is doing.$event->getData()