Adding Query Parameters with ZF2 URL Helper

In a view script in Zend Framework 2, one may need to generate an URL for a given route that includes one or more query parameters. For instance, when browsing through a paginated data set, one may want a form’s action attribute to point to the current page, such that the user will end on the same page upon postback. This can be accomplished with ZF2’s URL view helper.


// Result: /routeName?page=X
echo $this->url('routeName', array(), array(
    'query' => array(
        'page' => $currentPageNumber,
    ),
));

If you want to include route parameters, then simply add them to the array that is passed as the second argument to the view helper.

Similarly, the same can be done when redirecting within a controller by using the redirect controller plugin as shown below.


public function messagesAction()
{
    $this->redirect()->toRoute('routeName', array(), array(
        'query' => array(
            'page' => $currentPageNumber,
        ),
    ));
}

I hope this short article helped someone solve this problem. Thank you for reading!

5 Comments

  1. Franco said:

    Thanks for your post, it works for me!!!!!!

    November 21, 2014
    Reply
  2. Attila Naghi said:

    how can I pass an array as a paramater ?

    January 4, 2015
    Reply
  3. Chriz said:

    Helped me out, thanks.

    March 24, 2015
    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *