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

前端 未结 2 451
一向
一向 2020-12-08 04:46

I\'m trying to access the entity for a given embedded form in the parent CollectionType inside FormBuilder:

ParentType

2条回答
  •  不知归路
    2020-12-08 05:21

    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
    
                }
            }
        );
    }
    

提交回复
热议问题