mattalxndr
mattalxndr

Reputation: 9418

In Symfony2, how can I refresh the page, changing just one parameter of the GET string?

How can I refresh the page, changing one parameter of the GET string?

Say I'm on this page:

/my/page?foo=bar&asd=qwe

And in the controller, I have this variable:

$var = array('foo' => 'woof');

How can I use that variable to redirect to this page?:

/my/page?foo=woof&asd=qwe

Or if I'm on this page:

/my/page

Using that variable, how do I get to this page?:

/my/page?foo=woof

Upvotes: 2

Views: 1431

Answers (2)

jachim
jachim

Reputation: 61

public function onKernelRequest(GetResponseEvent $event) {
    $request = $event -> getRequest();
    $routes = $this -> router -> getRouteCollection();
    $routeName = $request -> get("_route");
    $params = $request -> query -> all();
    $route = $routes -> get($routeName);
    preg_match_all("/{(.+)}/", $route -> getPattern(), $routeParams);
    $routeParams = $routeParams[1];
    foreach ($routeParams as $key => $value) {
        $params[$value] = $request -> get($value);
    }

    if (array_key_exists("to_remove", $params)) {
        unset($params['to_remove']);
        $url = $this -> router -> generate($routeName, $params);
        $event -> setResponse(new RedirectResponse($url));
    }
}

Upvotes: 0

Guillaume Flandre
Guillaume Flandre

Reputation: 8980

If I understand well, what you want to do is the following:

public function myAction()
{
    $request = $this->getRequest();
    $params = $request->query->all();  // get the original GET parameters

    $var = array('foo' => 'woof');
    $newParams = array_replace($params, $var); // only replaces the 'foo' parameter, keeping the rest as is

    $url = '/my/page?'.http_build_query($newParams); // you can also use $this->generateUrl() if you use routing (which would be a good idea)

    return $this->redirect($url);
}

Upvotes: 2

Related Questions