Question

I am trying to add module specific navigation items from within the module. I may be doing this completely wrong. What I have so far is:

config/autoload/navigation.global.php (this works so far)

<?php
return array(
  'navigation' => array(
    'default' => array(
      array(
        'label' => 'Home',
        'route' => 'home',
        'order' => -100,
        'pages' => array(
        ),
      ),
    ),
  ),
);

module/Books/Module.php: (I am trying to add 'Books' navigation items under Home (not inline with))

class Module
{
  public function onPreDispatch($e) {
    $pages = array(
      array(
        'label' => 'Books',
        'route' => 'books',
      ),
    );
    $navigation = $e->getParam('application')->getServiceManager()->get('navigation');
    $navigation->findOneByRoute('home')->addPages($pages);
  }
  /* ... */
}

So in the above example (the route is correct), I do not get an error, the event trigger on pre-dispatch, but nothing gets added to the navigation container.

What I want to accomplish is Navigation as follows:

  Home
    |-> Books
    |-> Module2
    |-> etc..
Was it helpful?

Solution

You don't need to hook on an event. Just put the module specific navigation configuration in the module's module.config.php. The configuration of every module is merged and if you have caching this will be better in terms of performance if you do it for many modules.

Important is to give names to your items in the navigation. In config/autoload/navigation.global.php add a name for the home item:

<?php
return array(
    'navigation' => array(
        'default' => array(
            'home' => array(      // <-- name "home" added (name is arbitrary)
                'label' => 'Home',
                'route' => 'home',
                 'order' => -100,
            ),
        ),
    ),
);

and then in the module/Books/config/module.config.php

return array(
    'navigation' => array(
        'default' => array(
            'home' => array(
                'pages' => array(
                    'home/book' => array(   // <-- name is arbitrary
                        'label' => 'Books',
                        'route' => 'books',
                     ),
                 ),   
             ),
         ),
     ),
);

In the end both configurations merge and you have one navigation key:

return array(
    'navigation' => array(
        'default' => array(
            'home' => array(
                'label' => 'Home',
                'route' => 'home',
                'order' => -100,
                'pages' => array(
                    'home/book' => array(
                        'label' => 'Books',
                        'route' => 'books',
                     ),
                 ),   
             ),
         ),
     ),
);

Hope this helps :)

Stoyan

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top