Zend Framework Routes and Navigation

Having spent a few hours attempting to work out why Zend_Navigation was refusing to place the built-in “active” css class onto my navigation elements while being in the correct module/controller/action I finally resolved the issue:

It came down the custom routes!

If you have custom routes and you find your navigation is not correctly highlighting  it’s probably because you haven’t tied in your route to your navigation elements.

It requires very explicit setting to work.

Below is an example of how it should be structured:

Your routes.xml:
<routes>
 <example>    
  <example_demo>
   <type>Zend_Controller_Router_Route</type>
   <route>/example/custom/route</route>
   <defaults>
     <module>example</module>
     <controller>index</controller>
     <action>index</action>
   </defaults>
  </example_demo>
 </example>
</routes>

To load your routes into the router:
// Grab the default routes config.
 $config = new Zend_Config_Xml(dirname(__FILE__) . '/configs/routes.xml');
 // Get the front controller.
 $front = Zend_Controller_Front::getInstance();

 // Get the router.
 $router = $front->getRouter();
 // Add the config into the router under 'routes'
 $router->addConfig($config, 'example');

To tie into your navigation you require the following to be set explicitly.

$primaryNavigation = new Zend_Navigation();
// This applys the navigation to the registry for use by the view helper.
Zend_Registry::set('Zend_Navigation',$primaryNavigation);
$example = new Zend_Navigation_Page_Mvc();
$example->setModule('example');
$example->setController('index');
$example->setAction('index');
$example->setLabel('My Example Navigation Element');
$example->setRoute('example_demo');
// Add the new navigation element to the primary nav.
$primaryNavigation->addPage($example);

Calling
print $this->navigation()
should now render your whole navigation in the view template.

Now when you visit your /example/custom/route you should find the navigation element is correctly set with the “active” flag now.

Tags: ,

Leave a Reply