Search code examples
symfonysymfony-3.2

Symfony 3: in controller action, set a new request param then redirect


In a Symfony 3 controller action, I add a parameter to the request and then send it to another controller action via 307 redirect.

/**
 * @Route("/first", name="my_first_action")
 */
public function firstAction(Request $request)
{
    $request->request->set('new_param', 1);

    dump($request->request->all()); // new param is present

    return $this->redirectToRoute('my_second_action', [
        'request' => $request
    ], 307);
}

After redirect the new parameter is not in the request.

/**
 * @Route("/second", name="my_second_action")
 */
public function secondAction(Request $request)
{
    dump($request->request->all()); // new param is not present
    exit;
}

How do I add a parameter to the request so that it is available when the request gets passed to a new action via 307 redirect?


Solution

  • You can't pass objects like that in the redirect. But you can send you parameters in the array and handle them in the receiving route like so:

    /**
     * @Route("/first", name="my_first_action")
     */
    public function firstAction(Request $request)
    {
        return $this->redirectToRoute('my_second_action', [
            'new_param' => 1
        ], 307);
    }
    

    /**
     * @Route("/second/{new_param}", name="my_second_action")
     */
    public function secondAction($new_param)
    {
        dump($new_param));  // Either dump or use the parameter
        exit;
    }
    

    If you need more parameters, you can just add them to the Route.