将选项数组中的值传递给嵌入表单 [英] Pass value in options array to embedded form

查看:27
本文介绍了将选项数组中的值传递给嵌入表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解如何通过 createForm 方法将变量从控制器传递到表单,但是如果我需要将该值传递给嵌入在我称为表单中的表单该怎么办 createForm 上?我从来没有在嵌入表单的任何地方显式调用 createForm,那么我应该如何获得该值呢?值得注意的是,我尝试传递的值可通过服务获得,但我无法调用 $this->get('serviceName')->getValue() 因为我是不在控制器中.作为参考,这是我如何获取父表单的值,请注意我是如何通过 createForm 方法而不是构造函数来实现的:

I understand how to pass a variable from a controller to a form through the createForm method, but what if I need to pass that value to a form embedded in the form I am called createForm on? I never explicitly call createForm anywhere on the embedded form, so how am I supposed to get that value to it? It is worth noting the value I am trying to pass is available through a service, but I can't call $this->get('serviceName')->getValue() because I am not in a controller. For reference, this is how I get the value to the parent form, note how I do it through the createForm method, not the contructor:

//in a controller
$form = $this->createForm(new FormType(), $formObject, array('value' => $value));

推荐答案

并不是因为您不在控制器中而无法注入服务(和参数).尤其是在每种类型都可以是服务的类型中.当然,您不能直接执行 $this->get('serviceName')->getValue() 因为方法 get 在默认情况下不可用.但是,您可以将服务注入到您的表单类型中.请参阅我在此处回答的关于依赖注入的另一个问题,了解有关如何注入服务的一些信息.

It's not because you are not in a controller that you cannot inject services (and parameters). Especially into types where each type can be a service. Sure, you can't do $this->get('serviceName')->getValue() directly because the method get is not available by default. However, you could inject the service into your form type. See another question I answered on dependency injection here for some information on how to inject services.

请参阅此 食谱部分,它告诉您如何将您的类型转换为服务,以便您可以注入依赖项,同时注入您的价值.

See this cookbook section which tells you how to transform your type into a service so you can inject your dependencies and at the same time, your value.

如果由于某种原因您无法将您的类型转换为服务,那么您需要做的是将您的选项传递给 FormType,后者将读取它们并传递 value 嵌入类型的选项.这就像一个传递样式设计,您将所有选项传递给主类型,主类型会将其中一些传递给每个子类型,然后每个子类型将它们传递给它们自己的子类型等等.同样,您可以查看此 [食谱食谱],了解如何阅读选项并在自定义表单类型中使用它们.

If for some reason you cannot transform your type into a service, then what you need to do is to pass your options to FormType which will read them and pass the value option to the embedded type. It is like a passing style design, you pass all you options to the main type, which will pass some of them to each sub types, than each sub types will pass them to their own sub types and so on. Again, you can take a look at this [cookbook recipe] for how to read options and use them in a custom form type.

总而言之,我认为将您的类型转换为服务更容易.

In conclusion, I think it is easier to transform your type into a service.

希望对你有帮助.

问候,
马特

这篇关于将选项数组中的值传递给嵌入表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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