Friday, June 11, 2010

Layout and Navigation, Part 2

In Part 1 of this series, I modified the ZF quickstart application to use Zend_Layout for an application-wide template. Part 2 will add a menu to the left sidebar of that template using Zend_Navigation.

Create a new file in the /application/configs directory called navigation.xml. Here is the content:
<?xml version="1.0" encoding="UTF-8"?>
<configdata>
<nav>
<content>
<label>Content Index</label>
<controller>content</controller>
<action>index</action>
<pages>
<page1>
<label>Page 1</label>
<controller>content</controller>
<action>page1</action>
</page1>
<page2>
<label>Page 2</label>
<controller>content</controller>
<action>page2</action>
</page2>
<page3>
<label>Page 3</label>
<controller>content</controller>
<action>page3</action>
</page3>
<page4>
<label>Page 4</label>
<controller>content</controller>
<action>page4</action>
</page4>
<page5>
<label>Page 5</label>
<controller>content</controller>
<action>page5</action>
</page5>
</pages>
</content>
</nav>
</configdata>
To use this XML file for creating the Zend_Menu requires adding an _initNavigation() function to the Bootstrap.php file. The Bootstrap file is a place to section out all the different application initialization methods. All of these are automatically run when $application->bootstrap()->run(); is called in index.php, or they can be selected and run individually (perhaps for other configurations such as web services or test) by calling $application->getBootstrap()->bootstrap('method_name'); at any time.

Here is the method you will want to add to initialize your navigation:
protected function _initNavigation()
{
// read in the xml menu
$xml = new Zend_Config_Xml(APPLICATION_PATH . '/configs/navigation.xml', 'nav');

// initialize the navigation object with the xml
$container = new Zend_Navigation($xml);

// Set the navigation object to the view
$view = Zend_Layout::getMvcInstance()->getView();
$view->navigation($container);
}
Now go back to your layout from Part 1 and replace the "menu goes here" text with this:
<?php
echo $this->navigation()->menu();
?>
One note here is that you should be developing in your development environment. If not, you will not get the errors and warning messages you may need to debug your menus. That is because the development section of application.ini includes these lines:
phpSettings.display_startup_errors = 1
phpSettings.display_errors = 1
resources.frontController.params.displayExceptions = 1
Now that the navigation is loading correctly and the menus are rendering, lets add a breadcrumb to the header just to show how easy this is. Replace the Header div in layout.phtml with the following:
<div id="Header">
MySite:
<?php
echo $this->navigation()->breadcrumbs()->setMinDepth(0)->render();
?>
</div>
That's all for now. Happy coding!

No comments:

Post a Comment