GotBatteries
GotBatteries

Reputation: 1386

How to forward with GET parameters?

How to forward with GET parameters?

I have two actions in same controller. I do some magic in the first action, and if all goes well, I want it to forward to the other one, but with GET parameters created in the first one.

What I have now is this:

return $this->forward('AppBundle:default:tracked', array(), array(
                    'tracking_code' =>  $tracking_code,
                    'company'       =>  $tp_company_name
            )));

Empty array in there because of a desperate effort to get it to work. Documentation tells that second array is for the query parameters, but nothing really happens, so I must be doing something wrong.

The second action tries to get the parameters like this:

/**
* @Route("/tracked", name="tracked")
*/
public function trackedAction()
{
    $request = Request::createFromGlobals();
    // If there is the required variables in the GET:
    if($request->query->has('tracking_code') && $request->query->has('company'))

But no, variables never get there it seems.

Reason I have this kind of setup, is that user can get into the trackedAction from another place as well.

Upvotes: 4

Views: 1687

Answers (2)

user4545769
user4545769

Reputation:

The way that Symfony controller forwarding works is by duplicating the current the Request with the options that you pass and then re-dispatching it through the HttpKernel component. You can see this in the code. Because it's a sub-request, your second action is creating a Request from globals (i.e. $_GET etc.) which haven't changed.

The solution is to change your second action method signature to:

public function trackedAction(Request $request)

This means that the $request variable will be "local" to your action and will contain the variables you want.

In practice you should always pass the Request in to your actions this way as it makes your controllers a lot more testable and prevents strange issues like this.

Alternatively to all of the above, you could use a redirect instead which would do an HTTP redirect rather than just forwarding within the Symfony request system.

Upvotes: 2

Guillaume Fache
Guillaume Fache

Reputation: 813

I think the proper way to get your parameters in your second action would be to do like this :

return $this->forward('AppBundle:default:tracked', array(
                'tracking_code' =>  $tracking_code,
                'company'       =>  $tp_company_name
        )));

And your second action would be :

/**
* @Route("/tracked/{tracking_code}/{company}", name="tracked")
*/
public function trackedAction($tracking_code=null, $company=null)
{
    ...
}

I used the $tracking_code = null because you specified this could be accessed from another place, that maybe does not provide these parameters. This way it works for both of them.

Hope this helps.

Upvotes: 3

Related Questions