I have and entity A which relates oneToMany with entity B. I want the user to have the option of selecting from existing B entities or create a new one on the form of type A. So far I have this on my form:
->add('ExistingB', 'entity', array(
'class' => 'AppBundle\Entity\B',
'required' => false,
'property_path' => 'B',
'mapped' => false,
))
->add('newB', new BType(), array(
'required' => false,
'property_path' => 'B',
'mapped' => false,
));
$builder->addEventListener(
FormEvents::POST_SUBMIT , function (FormEvent $event) {
$formB= $event->getForm()->get('newB');
if ($formB->get('name')->getData() != null){
//here I need to somehow say to the form that it needs to set mapped true
//to the formB field so it can create a new entity and update the relationship
}else{
//here I need to do the same but with the ExistingB field
}
}
);`
I cant find how to change the mapped attribute, and the times I got it, it doesn't create the entity. I suppose that's because in the post_submit event its too late for changes on the fields since the data is already downloaded to the A entity.
But.. if I use the pre_submit event, then I can't get the data of the child formB, since it always gives me null when I ask for it.
So... where is my big mistake?
Somebody can show me another way to deal with new or existing feature in symfony2 forms. I really can't believe that it could be that hard to implement so common behavior.
you can use pre submit event, you just have to do this like this: https://github.com/LPodolski/selectOrCreateOptionForm/blob/master/src/AppBundle/Form/ItemType.php#L36
full project that demonstrates how this should work: https://github.com/LPodolski/selectOrCreateOptionForm
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With