Adding Query Parameters with ZF2 URL Helper

Published on June 12, 2014 by

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!

Featured

Learn Zend Framework today!

Take an online course and become a ZF2 ninja!

Here is what you will learn:

  • Understand the theory of Zend Framework in details
  • How to implement an enterprise-ready architecture
  • Develop professional applications in Zend Framework
  • Proficiently work with databases in Zend Framework
  • ... and much more!
Zend Framework logo
Author avatar
Bo Andersen

About the Author

I am a back-end web developer with a passion for open source technologies. I have been a PHP developer for many years, and also have experience with Java and Spring Framework. I currently work full time as a lead developer. Apart from that, I also spend time on making online courses, so be sure to check those out!

5 comments on »Adding Query Parameters with ZF2 URL Helper«

  1. Franco

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

  2. Attila Naghi

    how can I pass an array as a paramater ?

  3. Chriz

    Helped me out, thanks.

Leave a Reply

Your e-mail address will not be published.