草庐IT

php - 通过服务将 Symfony EntityManager 注入(inject)到表单类型中

coder 2024-04-11 原文

我需要根据实体是否是最新发布的版本来修改表单中的某些字段(标签和类)。所以我需要能够将实体管理器注入(inject)到我的 formType 中,以便在事件监听器中我可以将当​​前版本与实体的已发布版本进行比较。但我什至无法将 entityManager 放入 __construct() 开始。也许还有更好的方法来实现我的大目标(例如修改 twig 模板中的表单),但我还需要了解如何进行这种基本的依赖注入(inject)。

我想如果我在我的服务中声明它(就像文档描述的基本 Service Container 和特别是 Constructor Injection 方法),它将作为我的构造中的参数可用。但是当我这样做时,我得到了错误:

可捕获的 fatal error :传递给 Gutensite\CmsBundle\Form\Type\ViewType::__construct() 的参数 1 必须是 Doctrine\ORM\EntityManager 的一个实例,未给出,在/var/www/core 中调用/cms/src/Gutensite/ArticleBundle/Controller/AdminEditController.php 第 222 行,定义在/var/www/core/cms/src/Gutensite/CmsBundle/Form/Type/ViewType.php 第 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);

注意:

我使用了两个实体管理器,所以我的 config.yml 看起来像这样。我不知道这对我注入(inject)的内容是否有任何影响,即我可以注入(inject) @doctrine.orm.entity_manager 还是应该注入(inject) @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%"

已引用:

解决方案:

我不需要将 ViewType 定义为服务,我只需要在创建新的 ViewType 表单时通过 new viewType($em) 传入实体管理器:

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);

最佳答案

你得到那个错误是因为你正在创建这样的表单类型:

$form = $this->createForm(new ViewType(), $view);

您创建新对象 ViewType 时不带任何参数,需要使用 EntityManager 调用它。您可以简单地从 Controller 传递实体管理器,如下所示:

$em = $this->get('doctrine.orm.entity_manager'); // or doctrine.orm.billing_entity_manager
$form = $this->createForm(new ViewType($em), $view);

在这种情况下,您甚至不需要将此表单类型定义为服务。

doctrine.orm.entity_managerdoctrine.orm.billing_entity_manager 的使用取决于您需要在 ViewType 中获取什么 -(来自女巫数据库)。

更新:

将表单类型定义为服务。

将这两项服务添加到您的配置中(services.yml):

services
    gutensite_cms.form.view:
        factory_method: createNamed
        factory_service: form.factory
        class: Symfony\Component\Form\Form
        arguments:
            - view_form                        # name of the form
            - view                             # alias of the form type
            - null                             # data to bind, this is where your entity could go if you have that defined as a service
            - { validation_groups: [Default] } # validation groups

    gutensite_cms.form.type.view:
        class: Gutensite\CmsBundle\Form\Type\ViewType
        arguments: [ "@doctrine.orm.entity_manager" ]
        tags:
            - { name: form.type, alias: view }

然后您可以通过在您的 Controller (或任何具有 container)中执行此操作来创建新表单,而无需手动传递任何参数(它们将自动注入(inject)):

public function newAction()
{
    $view = ...;
    $form = $this->get( 'gutensite_cms.form.view' );

    // set initial form data if needed
    $form->setData( $view );
}

关于php - 通过服务将 Symfony EntityManager 注入(inject)到表单类型中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24876767/

有关php - 通过服务将 Symfony EntityManager 注入(inject)到表单类型中的更多相关文章

  1. ruby - 使用 ruby​​ 和 savon 的 SOAP 服务 - 2

    我正在尝试使用ruby​​和Savon来使用网络服务。测试服务为http://www.webservicex.net/WS/WSDetails.aspx?WSID=9&CATID=2require'rubygems'require'savon'client=Savon::Client.new"http://www.webservicex.net/stockquote.asmx?WSDL"client.get_quotedo|soap|soap.body={:symbol=>"AAPL"}end返回SOAP异常。检查soap信封,在我看来soap请求没有正确的命名空间。任何人都可以建议我

  2. ruby - 具有身份验证的私有(private) Ruby Gem 服务器 - 2

    我想安装一个带有一些身份验证的私有(private)Rubygem服务器。我希望能够使用公共(public)Ubuntu服务器托管内部gem。我读到了http://docs.rubygems.org/read/chapter/18.但是那个没有身份验证-如我所见。然后我读到了https://github.com/cwninja/geminabox.但是当我使用基本身份验证(他们在他们的Wiki中有)时,它会提示从我的服务器获取源。所以。如何制作带有身份验证的私有(private)Rubygem服务器?这是不可能的吗?谢谢。编辑:Geminabox问题。我尝试“捆绑”以安装新的gem..

  3. ruby-on-rails - Rails 编辑表单不显示嵌套项 - 2

    我得到了一个包含嵌套链接的表单。编辑时链接字段为空的问题。这是我的表格:Editingkategori{:action=>'update',:id=>@konkurrancer.id})do|f|%>'Trackingurl',:style=>'width:500;'%>'Editkonkurrence'%>|我的konkurrencer模型:has_one:link我的链接模型:classLink我的konkurrancer编辑操作:defedit@konkurrancer=Konkurrancer.find(params[:id])@konkurrancer.link_attrib

  4. ruby - 通过 rvm 升级 ruby​​gems 的问题 - 2

    尝试通过RVM将RubyGems升级到版本1.8.10并出现此错误:$rvmrubygemslatestRemovingoldRubygemsfiles...Installingrubygems-1.8.10forruby-1.9.2-p180...ERROR:Errorrunning'GEM_PATH="/Users/foo/.rvm/gems/ruby-1.9.2-p180:/Users/foo/.rvm/gems/ruby-1.9.2-p180@global:/Users/foo/.rvm/gems/ruby-1.9.2-p180:/Users/foo/.rvm/gems/rub

  5. ruby - 通过 erb 模板输出 ruby​​ 数组 - 2

    我正在使用puppet为ruby​​程序提供一组常量。我需要提供一组主机名,我的程序将对其进行迭代。在我之前使用的bash脚本中,我只是将它作为一个puppet变量hosts=>"host1,host2"我将其提供给bash脚本作为HOSTS=显然这对ruby​​不太适用——我需要它的格式hosts=["host1","host2"]自从phosts和putsmy_array.inspect提供输出["host1","host2"]我希望使用其中之一。不幸的是,我终其一生都无法弄清楚如何让它发挥作用。我尝试了以下各项:我发现某处他们指出我需要在函数调用前放置“function_”……这

  6. ruby - 通过 ruby​​ 进程共享变量 - 2

    我正在编写一个gem,我必须在其中fork两个启动两个webrick服务器的进程。我想通过基类的类方法启动这个服务器,因为应该只有这两个服务器在运行,而不是多个。在运行时,我想调用这两个服务器上的一些方法来更改变量。我的问题是,我无法通过基类的类方法访问fork的实例变量。此外,我不能在我的基类中使用线程,因为在幕后我正在使用另一个不是线程安全的库。所以我必须将每个服务器派生到它自己的进程。我用类变量试过了,比如@@server。但是当我试图通过基类访问这个变量时,它是nil。我读到在Ruby中不可能在分支之间共享类变量,对吗?那么,还有其他解决办法吗?我考虑过使用单例,但我不确定这是

  7. ruby - 通过 RVM (OSX Mountain Lion) 安装 Ruby 2.0.0-p247 时遇到问题 - 2

    我的最终目标是安装当前版本的RubyonRails。我在OSXMountainLion上运行。到目前为止,这是我的过程:已安装的RVM$\curl-Lhttps://get.rvm.io|bash-sstable检查已知(我假设已批准)安装$rvmlistknown我看到当前的稳定版本可用[ruby-]2.0.0[-p247]输入命令安装$rvminstall2.0.0-p247注意:我也试过这些安装命令$rvminstallruby-2.0.0-p247$rvminstallruby=2.0.0-p247我很快就无处可去了。结果:$rvminstall2.0.0-p247Search

  8. ruby - Infinity 和 NaN 的类型是什么? - 2

    我可以得到Infinity和NaNn=9.0/0#=>Infinityn.class#=>Floatm=0/0.0#=>NaNm.class#=>Float但是当我想直接访问Infinity或NaN时:Infinity#=>uninitializedconstantInfinity(NameError)NaN#=>uninitializedconstantNaN(NameError)什么是Infinity和NaN?它们是对象、关键字还是其他东西? 最佳答案 您看到打印为Infinity和NaN的只是Float类的两个特殊实例的字符串

  9. ruby - 检查方法参数的类型 - 2

    我不确定传递给方法的对象的类型是否正确。我可能会将一个字符串传递给一个只能处理整数的函数。某种运行时保证怎么样?我看不到比以下更好的选择:defsomeFixNumMangler(input)raise"wrongtype:integerrequired"unlessinput.class==FixNumother_stuffend有更好的选择吗? 最佳答案 使用Kernel#Integer在使用之前转换输入的方法。当无法以任何合理的方式将输入转换为整数时,它将引发ArgumentError。defmy_method(number)

  10. ruby-on-rails - 启动 Rails 服务器时 ImageMagick 的警告 - 2

    最近,当我启动我的Rails服务器时,我收到了一长串警告。虽然它不影响我的应用程序,但我想知道如何解决这些警告。我的估计是imagemagick以某种方式被调用了两次?当我在警告前后检查我的git日志时。我想知道如何解决这个问题。-bcrypt-ruby(3.1.2)-better_errors(1.0.1)+bcrypt(3.1.7)+bcrypt-ruby(3.1.5)-bcrypt(>=3.1.3)+better_errors(1.1.0)bcrypt和imagemagick有关系吗?/Users/rbchris/.rbenv/versions/2.0.0-p247/lib/ru

随机推荐