Adding Query Parameters with ZF2 URL Helper
Published on June 12, 2014 by Bo Andersen
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!
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!
5 comments on »Adding Query Parameters with ZF2 URL Helper«
Thanks for your post, it works for me!!!!!!
how can I pass an array as a paramater ?
Helped me out, thanks.
You are welcome. Glad it helped. :-)
Thanks man, you’ve saved my day.