Steven Mercatante
Steven Mercatante

Reputation: 25295

Best way to get request object from within Symfony forms?

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?

Upvotes: 2

Views: 2894

Answers (1)

Maerlyn
Maerlyn

Reputation: 34107

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

Upvotes: 3

Related Questions