I'm trying to access the entity for a given embedded form in the parent CollectionType
inside FormBuilder
:
ParentType
Class ParentType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('children', CollectionType::class, array(
'entry_type' => ChildType::class
);
}
}
ChildType
class ChildType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$child = $builder->getData(); // this returns null
}
public function getDefaultOptions(array $options)
{
return array(
'data_class' => 'Vendor\Bundle\Entity\Child',
);
}
}
While this works in a normal form, $child
is being returned as null. How can I access the Child
entity inside ChildType
?
The answer lies in using Event Listeners which listen for the
PRE_SET_DATA
event.It will pass your closure a
FormEvent
class which contains both the form and the data being bound to it.This is a more detailed solution based on user1207727.
Parent Type
Child Type
Create form in controller