2

In Symfony, it is easy to get the request within a controller:

$request = $this->container->get('request');

Now, I suppose this is a bad practice...but is it possible to modify that request, meaning, for example modify the value of a hidden form field before binding it:

$requestModifiedWithNewValueForHiddenFormField = $request;
// modify the request
// ....
$this->bind($requestModifiedWithNewValueForHiddenFormField);

I suppose I should be using dataTransformer but in this case, I'd like to have your opinion on modifying a request...

Mick
  • 30,759
  • 16
  • 111
  • 130

2 Answers2

7

For quick request field modification you can do,

$request = $this->getRequest()->request;
$requestArray = $request->all();
$requestArray['nested']['modifying_field'] = "Modified value";
$request->replace($requestArray);

If the field is not nested then you can do it following way,

$this->getRequest()->request->set("modifying_field", "Modified value");
Mun Mun Das
  • 14,992
  • 2
  • 44
  • 43
1

It depends on what You want to achieve.

When this logic (modifying hidden file) will be common for more than one controller You should use definitely some dry approach like dataTransformer or events subscribers:

http://symfony.com/doc/current/cookbook/form/dynamic_form_generation.html

You can also inject request to your form and create form method to handle this.

Luke Adamczewski
  • 395
  • 3
  • 14
  • Thanks @Lukasz just wondering, How would you inject request to the form and create a form method to handle this? I mean where would you write the method and modify the field? – Mick Aug 21 '12 at 12:46
  • this is described here http://stackoverflow.com/questions/7643391/symfony2-access-the-container-in-the-repository – Luke Adamczewski Aug 21 '12 at 12:48
  • I wanted to say a big thank you @Lukasz, and I really mean it. Your answer really helped me a lot as I didn't know a lot about form events. I have voted +1 for the clarity of your answer. That's a shame we can't accept 2 answers on SO, but if we could, I would have done it. Many thanks. – Mick Aug 21 '12 at 15:13