How do I pass an object manager to an embed form in Symfony?

I can do it $this->createForm(new EntityType(), $entity, array('em' => $em))from the controller, but how do I pass it to NestedEntityType()? I think I can’t just pass it inside 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 object manager to set up a data transformer to check if an entity exists in the database and use this object in a relationship instead of creating a new one with the same name.

Resources

+4
source share
3 answers

, Doctrine .

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

:

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

:

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

options :

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
        'options' => array('em' => $entityManager) // <-- THIS
    ));
}

, @Johann -, , . ( )

+6

@Johann, Symfony 3, :

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

Source: https://habr.com/ru/post/1532020/


All Articles