在Symfony2中,如何刷新页面,只更改GET字符串的一个参数?

时间:2012-06-11 15:44:41

标签: symfony get request query-string

如何刷新页面,更改GET字符串的一个参数?

说我在这个页面上:

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

在控制器中,我有这个变量:

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

如何使用该变量重定向到此页面?:

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

或者如果我在这个页面上:

/my/page

使用该变量,我该如何访问此页面?:

/my/page?foo=woof

2 个答案:

答案 0 :(得分:2)

如果我理解得很好,你想要做的是:

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);
}

答案 1 :(得分:0)

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));
    }
}