如何将实体管理器传递给Symfony中的嵌入表单?

时间:2014-03-16 14:16:49

标签: php symfony

我可以从控制器执行$this->createForm(new EntityType(), $entity, array('em' => $em)),但如何将其传递给NestedEntityType()?我想我无法从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
    ));
}

我需要实体管理器来设置数据转换器以检查数据库中是否已存在实体,并在关系中使用该实体,而不是创建具有相同名称的新实体。

资源

3 个答案:

答案 0 :(得分:7)

您可以将表单定义为服务,然后将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();
}

答案 1 :(得分:6)

您可以使用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 的解决方案也是如此,所以值得花时间去做他提出的建议。我的解决方案更适合传递中间控制器的数据(不是服务)

答案 2 :(得分:1)

参考@ Johann的回答,如果你正在使用Symfony版本3,你需要在参数之间包装参数:

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