Symfony 3-将表单定义为服务 [英] Symfony 3 - Define form as a service

查看:70
本文介绍了Symfony 3-将表单定义为服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Symfony 3-master项目中,我使用以下代码在控制器中创建表单:

in my Symfony 3-master project, I use this code to create a form in a controller:

$form = $this->createForm(ApplicantType::class, $applicant);

现在,我决定使用这种形式提供服务,因此可以在其中使用EntityManager.因此,在Symfony2.x中,这很简单,只需在services.yml中声明,并使用以下代码行即可:

Now I decided to make a service out of this form, so I can use EntityManager inside of it. So in Symfony2.x, this would be pretty easy, just with a declaration in services.yml and this line of code:

$form = $this->createForm($this->get("applicant.form"), $applicant);

但是,在Symfony 3中不再可能,因为第一个参数需要字符串,而不是表单本身.

However, this is no longer possible in Symfony 3, because this first parameter expect a string, not the form itself.

所以我的问题是:如何在Symfony 3中将表单创建为服务,或者还有其他方法如何在表单内部传递EntityManager?

So my question is: How do I create a form as a service in Symfony 3, or is there any other way how to pass EntityManager inside of the form?

谢谢您的帮助!

推荐答案

将表单类型定义为服务并不意味着将从容器检索到的实例传递给createForm.执行此操作时,就涉及表单组件而言,不涉及容器.

Defining a form type as service does not imply passing the instance retrieved from to container to createForm. when doing this, the container is not involved as far as the form component is involved.

要使用注册为服务的表单类型(带有form.type标记,以便表单组件知道它),只需按其名称(即Symfony 2.8+和在createFormFormBuilder::add中键入旧版本中的名称). 这正是对注册为服务的Symfony核心类型btw(textchoice等)执行的操作. 使用表单类型作为服务时,而不是没有依赖项并且隐式注册第一次使用时,控制器的代码完全不会更改.

To use a form type registered as a service (with the form.type tag so that the form component knows about it), you just just reference it by its name (i.e. the fully qualified class name in Symfony 2.8+ and the type name in older versions) in createForm or in FormBuilder::add. This is exactly what you do for Symfony core types btw (text, choice and so on), which are registered as services. the code of your controller does not change at all when using the form type as a service rather than having a form type without dependency and registered implicitly on first usage.

这篇关于Symfony 3-将表单定义为服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆