In Zend Framework 2, you might have routes that have child routes. For instance, a register route may be a child route of a user route. What if you wish to link to the child route by using the URL view helper? The view helper’s documentation is not of much help in this regard.
What you can do is to use the parent route’s name followed by a forward slash and then the child route’s name.
In the case of the previous example, the URL of the child route can be built like this:
Any parameters used in the route can be passed as an array as the second parameter. Here is the method signature of the URL view helper:
url($name, $urlParams, $routeOptions, $reuseMatchedParams)
Lastly, I just want to quickly point your attention to the last parameter, because I found this to be useful in some situations. As the name strongly indicates, the $reuseMatchedParams parameter adds the parameters that matched the route to the constructed URL. For example, you might want to specify that a form’s action attribute should point to the current page, which was matched with one or more parameters. Instead of having to make these parameters available in the view script via the controller, this can all be done automatically for us by passing true as the last parameter.
Let us say that a route profile requires two parameters, giving an URL of the structure /profile/123/abc. Below is demonstrated how one can easily use the URL view helper to build an URL which includes the route’s matched parameters.
echo $this->url('profile', array(), array(), true); // Output: /profile/123/abc
Hopefully you get the point. Thank you for reading.
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!