Search code examples
phpzend-frameworkzend-framework2zend-route

Zend Framework 2: Dynamic navigation and breadcrumbs


I made a navigation in Zend Framework 2 using a global file located in config/autoload. how can I get in this global file the route parameters?

I have tried this:

$helper = new Zend\View\Helper\ServerUrl();
$active_url = $helper->getHost();

but this returns the whole url. For exemle I have an url like this

www.mysite.com/controller/action/id/3

I need to know the id.

My global file return a navigation array that looks like this:

return array(
    'navigation' => array(
        'default' => array(
            array(
                'label'      => 'Home',
                'route'      => 'admin',
                'active'     => true,
                'resource'   => 'Admin\Controller\Index',
                'privilege' => 'index',
                'pages'     =>  array(
                    'label'  => 'My posts ',
                    'route'  => 'admin/default',
                    'params' => array(
                        'controller' => 'posts',
                        'action' => 'edit'
                    ),
                    'resource'  => 'Admin\Controller\Posts',
                    'privilege' => 'edit',
                ),
            )
        )
    )
);

It all work fine as long as the route doesn't contain parameters. If my url contain an ID parameters my menu link and the breadcrumbs are form just with the controller and action without ID and in the same.

So, instead of:

www.mysite.com/posts/edit/id/12

My link looks like:

www.mysite.com/posts/edit

Solution

  • What you are looking for is dynamic breadcrumbs. It is not so common to tie breadcrumbs to route params, but you can find a question with an answer here on stackoverflow.

    As also written in the documentation here there is since ZF2 version 2.2.0 a 'useRouteMatch' flag that you can set to true.

    Starting in version 2.2.0, if you want to re-use any matched route parameters when generating a link, you can do so via the “useRouteMatch” flag. This is particularly useful when creating segment routes that include the currently selected language or locale as an initial segment, as it ensures the links generated all include the matched value.

    Instead of manually passing your params arary the navigator will use the params from the RouteMatch. Thus you will have your id also available.

    array(
        'label' => 'My posts',
        'route' => 'admin/default',
        'useRouteMatch' => true
    ),
    

    Note You said you defined your navigation in a global file in the autoload/config folder. It would be better to implement the navigation in your module.config.php as shown here in this tutorial.