symfonysymfony-http-foundation

Changing the Request, retrieving data from the Session


Scenario:

I want him to see the page /myapp/myentity//list?entity_filter[search]=something&page=2

I'm trying to make the filters sticky to the user's session, so that when the user re-opens /myapp/myentity/list without any parameter he gets the last seen result, with the same filters and page number.

I followed this approach but I think it's highly deprecated because i am modifying the $request object and the $_GET superglobal (due to the pagination library that uses directly $_GET), despite it works.

/**
 * @Route("/myapp/myentity/list",  name="entity_list")
 * @Method({"GET"})
 */
public function myEntityListAction(Request $request) {
    if (0===$request->query->count()) { //querystring is empty
        $prev_query=$request->getSession()->get('my_entity_list', null);
        if ($prev_query) { //is there something in session?
            $_GET=$prev_query;
            $original_request=$request;
            $request=$request->createFromGlobals();
            $request->setSession($original_request->getSession());
        }
    } else { //i have something in my querystring
        $request->getSession()->set('my_entity_list', $request->query->all()); //i store it in session
    }
    //...do the other stuff (form, filters, pagination, etc)
}

I think that i will follow another approach, redirecting the user to /myapp/myentity/list?entity_filter[search]=something&page=2 (reading from the session) so that i don't have to modify either $_GET or $request.

Here comes the question: How could I safely edit the $request to inject or change something I need without doing a redirect? Could I safely do it with a subrequest?


Solution

  • You could use Before filter for that. In the listener, check your session, extract saved path (or filters) and just redirect (if you want) using something like

    $event->setController(function() use ($redirectUrl) {
        return new RedirectResponse($redirectUrl);
    });
    

    Also you can get request using $event->getRequest() and change it as you want.