Php 如何将实体管理器传递给Symfony中的嵌入表单?
我可以从控制器执行Php 如何将实体管理器传递给Symfony中的嵌入表单?,php,symfony,Php,Symfony,我可以从控制器执行$this->createForm(new EntityType(),$entity,array('em'=>$em)),但如何将其传递给NestedEntityType()?我想我不能从EntityType->buildForm()内部传递它: 我需要实体管理器设置一个数据转换器来检查数据库中是否已经存在实体,并在关系中使用该实体,而不是创建一个同名的新实体 资源 您可以将表单定义为服务,然后将Doctrine entity manager作为参数插入其中 然后像
$this->createForm(new EntityType(),$entity,array('em'=>$em))
,但如何将其传递给NestedEntityType()
?我想我不能从EntityType->buildForm()
内部传递它:
我需要实体管理器设置一个数据转换器来检查数据库中是否已经存在实体,并在关系中使用该实体,而不是创建一个同名的新实体
资源
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();
}
您可以使用
选项
将相应的数据传递给子类型:
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
));
}
public function buildForm(formbuilder接口$builder,数组$options)
{
$entityManager=$options['em'];
$builder->add('实体','集合',数组(
'type'=>new NestedEntityType(),
“允许添加”=>true,
“允许删除”=>true,
“按引用”=>错误
'options'=>array('em'=>$entityManager)/参考@Johann的答案,如果您使用的是Symfony版本3,则需要将参数括在引号之间:
services:
acme.type.employee:
class: Acme\AcmeBundle\Form\Type\FormType
tags:
- { name: form.type, alias: form_em }
arguments: ["@doctrine"]
1.FormType
扩展了没有构造函数的AbstractType
,因此调用parent::\uu construct()
会导致致命错误。2.是否有任何理由使管理器在对象范围内可用,或者可以将其放入buildForm()中
函数?3.什么名称空间应该用于原则
类名?为什么不在表单类型中仅使用EntityManager
,如?1.然后删除这一行。2.我不认为将其放在buildForm()中
函数将起作用,因为服务的参数在创建时被注入到其构造函数中。3.使用条令\Bundle\DoctrineBundle\Registry作为条令;
您可以像另一个答案一样直接注入实体管理器,没有真正的区别,这只是获得实体管理的许多不同方法中的两种r、 我将用这些更正编辑我的答案。
services:
acme.type.employee:
class: Acme\AcmeBundle\Form\Type\FormType
tags:
- { name: form.type, alias: form_em }
arguments: ["@doctrine"]