从 Symfony 表单中获取请求对象的最佳方法? [英] Best way to get request object from within Symfony forms?
问题描述
我使用 Symfony 和 Doctrine 为我的 CMS 生成表单.最近,我一直在通过基于特定 URL 参数设置默认值来自定义它们.
I use Symfony and Doctrine to generate forms for my CMSes. Lately I've been customizing them by setting default values based on specific URL parameters.
例如,我有两个模型:PollQuestion
和 PollChoice
.PollChoice
通过 poll_question_id
字段与 PollQuestion
相关联.PollChoice
表单有一个下拉列表,其中列出了 PollChoice
可以附加到的所有可用 PollQuestion
.我也有两条路线:pollchoices/new
和 poll/:poll_id/choice/new
.两个路由都显示 PollChoiceForm
,但是通过使用第二个路由,您将自动看到设置为 :poll_id
URL 参数的 PollQuestion 下拉列表.为此,我通过从请求对象中获取 :poll_id
的值来简单地更改 PollChoiceForm
类中下拉小部件的默认值.
For example, I have two models: PollQuestion
and PollChoice
. PollChoice
has a relation to PollQuestion
by means of a poll_question_id
field. The PollChoice
form has a dropdown that lists all the available PollQuestion
s that the PollChoice
can be attached to. I also have two routes: pollchoices/new
and poll/:poll_id/choice/new
. Both routes display the PollChoiceForm
, but by using the 2nd route you would automatically see the PollQuestion dropdown set to the :poll_id
URL parameter. I do this by simply changing the default value of the dropdown widget in the PollChoiceForm
class by fetching the value of :poll_id
from the request object.
我的问题有两个:
1) 我目前使用 sfContext::getInstance()->getRequest()
获取请求对象.我知道 sfContext::getInstance()
不受欢迎,但我一直无法找到另一种获取它的方法.还有其他方法吗?依赖注入似乎是一个不错的方法,但我不知道如何在不进行大量黑客攻击的情况下实现这一目标(我想避免这种情况).
1) I currently fetch the request object by using sfContext::getInstance()->getRequest()
. I know that sfContext::getInstance()
is frowned upon, but I haven't been able to find another way to fetch it. Is there another way? Dependency injection seems like a good way to go, but I don't know how to accomplish that without doing a lot of hacking (which I'd like to avoid).
2) 根据 URL 参数更改表单默认值的方式是否完全错误?
2) Am I completely going about the wrong way of changing a form's default values based on URL parameters?
推荐答案
每当我需要表单中的上下文时,我都会通过构造函数注入来实现.
Whenever I need the context in a form, I'm doing it via constructor injection.
在行动中:
$this->form = new WhateverForm($whatever, array("context" => $this->getContext()));
形式:
$this->getOption("context");
这篇关于从 Symfony 表单中获取请求对象的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!