Symfony form - Access Entity inside child entry Type in a CollectionType

Nick picture Nick · Mar 15, 2012 · Viewed 24.6k times · Source

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?

Answer

user1207727 picture user1207727 · Mar 16, 2012

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.

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->addEventListener(FormEvents::PRE_SET_DATA,
        function (FormEvent $event) use ($builder)
        {
            $form = $event->getForm();
            $child = $event->getData();

            if ($child instanceof Child) {

                // Do what ever you like with $child entity data

            }
        }
    );
}