我需要根据实体是否是最新发布的版本来修改表单中的一些字段(标签和类)。因此,我需要能够将实体管理器注入到我的 formType 中,以便在事件侦听器中我可以将当前版本与实体的已发布版本进行比较。但我什至无法得到entityManager
首先进入 __construct() 。也许还有更好的方法来实现我的大目标(例如修改树枝模板中的表单),但我还需要了解如何进行这种基本的依赖项注入。
我认为如果我在我的服务中声明它(就像基本文档中描述的那样)服务容器特别是构造函数注入方法),它将在我的构造中作为参数使用。但是当我这样做时,我收到错误:
Catchable fatal error: Argument 1 passed to Gutensite\CmsBundle\Form\Type\ViewType::__construct() must be an instance of Doctrine\ORM\EntityManager, none given, called in /var/www/core/cms/src/Gutensite/ArticleBundle/Controller/AdminEditController.php on line 222 and defined in /var/www/core/cms/src/Gutensite/CmsBundle/Form/Type/ViewType.php on line 15
以下是我的代码片段:
Gutensite/CmsBundle/Resources/config/service.yml
gutensite_cms.form.type.view:
class: Gutensite\CmsBundle\Form\Type\ViewType
arguments: [ "@doctrine.orm.entity_manager" ]
Gutensite/CmsBundle/Form/Type/ViewType.php
namespace Gutensite\CmsBundle\Form\Type;
use Doctrine\ORM\EntityManager;
use Symfony\Component\Form\AbstractType;
class ViewType extends AbstractType
{
private $em;
public function __construct(EntityManager $entityManager) {
$this->em = $entityManager;
}
}
Gutensite/ArticleBundle/Controller/AdminEditController.php
// Get the View Entity
$em = $this->getDoctrine()->getManager();
$viewRepo = $em->getRepository("GutensiteCmsBundle:View\View");
$view = $viewRepo->find($request->query->get('id'));
// Create the generic form for editing any View, using the view entity constructed
$form = $this->createForm(new ViewType(), $view);
NOTE:
我正在使用两个实体管理器,所以我的 config.yml 看起来像这样。我不知道这对我注射的内容是否有任何影响,即我可以注射吗@doctrine.orm.entity_manager
或者我应该注射@doctrine.orm.default_entity_manager
或者其他的东西?我尝试了各种选择,但没有一个有效。
# Doctrine Configuration
doctrine:
dbal:
default_connection: cms
connections:
cms:
driver: "%db.cms.driver%"
host: "%db.cms.host%"
port: "%db.cms.port%"
dbname: "%db.cms.name%"
user: "%db.cms.user%"
password: "%db.cms.password%"
charset: "%db.cms.charset%"
billing:
driver: "%db.billing.driver%"
host: "%db.billing.host%"
port: "%db.billing.port%"
dbname: "%db.billing.name%"
user: "%db.billing.user%"
password: "%db.billing.password%"
charset: "%db.billing.charset%"
orm:
default_entity_manager: cms
entity_managers:
cms:
connection: cms
mappings:
GutensiteCmsBundle: ~
GutensiteArticleBundle: ~
billing:
connection: billing
mappings:
GutensiteBillingBundle: ~
auto_generate_proxy_classes: "%kernel.debug%"
已经参考:
- Symfony 2 EntityManager 注入服务
- Symfony 在 FormType 中注入 EntityManager
解决方案:
我不需要将 ViewType 定义为服务,我只需要通过以下方式传入实体管理器new viewType($em)
当我创建新的 ViewType 表单时:
Gutensite/ArticleBundle/Controller/AdminEditController.php
// Get the View Entity
$em = $this->getDoctrine()->getManager();
$viewRepo = $em->getRepository("GutensiteCmsBundle:View\View");
$view = $viewRepo->find($request->query->get('id'));
// Create the generic form for editing any View, using the view entity constructed
$form = $this->createForm(new ViewType($em), $view);