Search code examples
symfonysymfony4sonata-adminsonata

Get parent entity id in CollectionType Admin


I am creating an entity basketElement which is linked to a parent entity basket via Sonata\Form\Type\CollectionType instantiated admin. When creating the entity basketElement I also need to call a function of a service which needs the id of entity basket.

For now, I have an admin:

class BasketAdmin extends AbstractAdmin {
    /**
     * @param \Sonata\AdminBundle\Form\FormMapper $formMapper
     */
    public function configureFormFields(FormMapper $formMapper): void
    {
        $formMapper->with('basket.group.basketElements')
            ->add('basketElements', Sonata\Form\Type\CollectionType::class)
        ;
    }
}

And the basketElements field admin is as following:

class BasketElementAdmin extends AbstractAdmin {
    /**
     * @param \Sonata\AdminBundle\Form\FormMapper $formMapper
     */
    public function configureFormFields(FormMapper $formMapper): void
    {
        $formMapper->with('basketElement.group.products')
            ->add('basket', Sonata\AdminBundle\Form\Type\ModelHiddenType::class)
        ;
    }

    public function prePersist(){
        $this->myService->myFunction($this->getParent()->getSubject()->getId());
    }
}

How can I access the parent entity?


Solution

  • I've found 2 solutions;

    • link_parameters can be added to fieldDescriptionOptions argument of the add method on the CollectionType field. Than in the basketElementAdmin one can retrieve the link parameter from the request object and use it to retrieve the linked entity.
        /**
         * @param \Sonata\AdminBundle\Form\FormMapper $formMapper
         */
        public function configureFormFields(FormMapper $formMapper): void
            {
                $formMapper->with('basket.group.basketElements')
                    ->add('basketElements', Sonata\Form\Type\CollectionType::class, [], [
                        'link_parameters' => ['basket_id' => $this->getSubject()->getId()]
                    ])
                ;
            }
        }
    
    • The function of service which needs the parent id can be called and set to the childAdmin in the prePersist and preUpdate methods of the parent admin