2

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 Answer 1

3

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");
Sign up to request clarification or add additional context in comments.

1 Comment

I like this method. I think I would edit my custom admin theme's actions to automatically inject it within the constructor.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.