Search code examples
phpsymfony1

Is there a Symfony helper for getting the current action URL and changing one or more of the query parameters?


What I'd like to do is take the route for the current action along with any and all of the route and query string parameters, and change a single query string parameter to something else. If the parameter is set in the current request, I'd like it replaced. If not, I'd like it added. Is there a helper for something like this, or do I need to write my own?

Thanks!

[edit:] Man, I was unclear on what I actually want to do. I want to generate the URL for "this page", but change one of the variables. Imagine the page I'm on is a search results page that says "no results, but try one of these", followed by a bunch of links. The links would contain all the search parameters, except the one I would change per-link.


Solution

  • Edit:

    Ok I got a better idea now what you want. I don't know whether it is the best way but you could try this (in the view):

    url_for('foo', 
            array_merge($sf_request->getParameterHolder()->getAll(), 
                        array('bar' => 'barz'))
    )
    

    If you use this very often I suggest to create your own helper that works like a wrapper for url_for.

    Or if you only want a subset of the request parameters, do this:

    url_for('foo', 
             array_merge($sf_request->extractParameters(array('parameter1', 'parameter3')),
                         array('bar' => 'barz'))
    )
    

    (I formated the code this way for better readability)


    Original Answer:

    I don't know where you want to change a parameter (in the controller?), but if you have access to the current sfRequest object, this should do it:

    $request->setParameter('key', 'value')
    

    You can obtain the request object by either defining your action this way:

    public function executeIndex($request) {
         // ...
    }
    

    or this

    public function executeIndex() {
         $request = $this->getRequest();
    }