Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass the entity manager to an embed form in Symfony?

Tags:

php

symfony

I can do $this->createForm(new EntityType(), $entity, array('em' => $em)) from the controller, but how can I pass it to a NestedEntityType()? I guess I can't just pass it on from inside the EntityType->buildForm():

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $entityManager = $options['em'];

    $builder->add('entities', 'collection', array(
        'type' => new NestedEntityType(),
        'allow_add' => true,
        'allow_delete' => true,
        'by_reference' => false
    ));
}

I need the entity manager to setup a data transformer to check if an entity already exists in the database, and use that entity in a relationship instead of creating a new one with the same name.

Resources

  • How to use Data Transformers
  • Embedded Forms
  • How to Embed a Collection of Forms
  • How to avoid duplicate entries in a many-to-many relationship with Doctrine?
like image 494
Gergő Avatar asked Dec 08 '22 09:12

Gergő


1 Answers

You could define your form as a service and then inject Doctrine entity manager in it as an argument.

http://symfony.com/doc/3.4/form/form_dependencies.html

And then declare the service like this:

services:
    acme.type.employee:
        class: Acme\AcmeBundle\Form\Type\FormType
        tags:
            - { name: form.type, alias: form_em }
        arguments: [@doctrine]

And in the form type:

use Doctrine\Bundle\DoctrineBundle\Registry as Doctrine;

/** @var \Doctrine\ORM\EntityManager */
private $em;

/**
 * Constructor
 * 
 * @param Doctrine $doctrine
 */
public function __construct(Doctrine $doctrine)
{
    $this->em = $doctrine->getManager();
}
like image 106
Johann Avatar answered Dec 10 '22 21:12

Johann