Best way to get request object from within Symfony forms?

邮差的信 提交于 2019-12-03 22:23:23

问题


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.

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 PollQuestions 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.

My question is two-fold:

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) Am I completely going about the wrong way of changing a form's default values based on URL parameters?


回答1:


Whenever I need the context in a form, I'm doing it via constructor injection.

in the action:

$this->form = new WhateverForm($whatever, array("context" => $this->getContext()));

in the form:

$this->getOption("context");


来源:https://stackoverflow.com/questions/6345437/best-way-to-get-request-object-from-within-symfony-forms

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!