2017-09-25 114 views

回答

1

将整个容器注入表单类型是一种不好的做法。请考虑仅向您的表单类型注入必需的依赖项。您可以简单地define your form type as a service并注入所需的依赖关系。

的src /的appbundle /表格/ TaskType.php

use Doctrine\ORM\EntityManagerInterface; 
// ... 

class TaskType extends AbstractType 
{ 
    private $em; 

    public function __construct(EntityManagerInterface $em) 
    { 
     $this->em = $em; 
    } 

    // ... 
} 

的src /的appbundle /资源/配置/ services.yml

services: 
    AppBundle\Form\TaskType: 
     arguments: ['@doctrine.orm.entity_manager'] 
     tags: [form.type] 

为了注射仓储类有两种方式。第二种方法更干净。使用EM工厂

$this->em->getRepository(User::class) 

注册库类的服务,并将它注入到你的表单类型:从EM

注入EntityManager类,并获得仓储类

services: 
    AppBundle\Repository\UserRepository: 
     factory: ['@doctrine.orm.entity_manager', getRepository] 
     arguments: ['AppBundle\Entity\User'] 
+0

我想从我的应用程序获取存储库 – webwinner

+0

更新了我的答案,并在服务中注入了Repository类。 –

1

的一个问题是通过集装箱作为参数传递给从控制器的FormType文件:

$form_type = new MyFormType($this->container); 

,并添加构建方法在你的FormType文件中:

protected $container; 

public function __construct($container) 
{ 
    $this->container = $container; 
} 

然后你可以通过'$ this-> container'来访问容器;

希望它能帮助你;)

+0

只有在他们使用古老版本的Symfony时。时代已经改变。 – Cerad

相关问题