Thursday, July 7, 2011

Zend Custom breadcrumb using XML file

As we know a breadcrumb can be generated using Zend_Navigation easily. But this will apply only to navigation menu items, not for other extra actions (outside from menu). Here i have overwrite Zend Navigation breadcrumb view helper, so that a separate XML file can be used for breadcrumb.

To implement this there are 6 simple steps. I have used Custom_ as namespace either change it to any namespace that you have used in your application or add this namespace in you application.

Step 1 : Create Custom_BreadCrumb class by extending Zend_Navigation_Container

class Custom_BreadCrumb extends Zend_Navigation_Container
* Creates a new bread container from zend navigation help
* @param array|Zend_Config $pages [optional] pages to add
* @throws Zend_Navigation_Exception if $pages is invalid
public function __construct($pages = null)
if (is_array($pages) || $pages instanceof Zend_Config) {
} elseif (null !== $pages) {
require_once 'Zend/Navigation/Exception.php';
throw new Zend_Navigation_Exception(
'Invalid argument: $pages must be an array, an ' .
'instance of Zend_Config, or null');

Step 2: Create an empty view helper class

class Custom_View_Helper_Breadcrumbs extends Zend_View_Helper_Navigation_Breadcrumbs{}

you can override some feature of breadcrumbs view helper inside this class.

Step 3: Create XML File name breadcrumb.xml inside application/config/breadcrumbs.xml

Step 4: Load breadcrumb in bootstrap

protected function _initViewHelpers() {
$layout = $this->getResource('layout');
$view = $layout->getView();
$breadCrubmConfig = new Zend_Config_Xml(APPLICATION_PATH . '/configs/breadcrumbs.xml');
$breadCrumb = new Custom_BreadCrumb($breadCrubmConfig);

Step 5: Now set the breadcrumb active state in super action controller class

Note: Super action controller class means, all the controller class in an application should extend this class.

$module = $this->_request->getModuleName();
$controller = $this->_request->getControllerName();
$action = $this->_request->getActionName();
$mca = $module.'/'.$controller.'/'.$action;
$activeBreadCrumbs = $this->view->breadcrumbs()->findBymca($mca);
$activeBreadCrumbs->active = true;

Step 6: Usage

Just paste this line in your layout

echo $this->breadcrumbs()->setSeparator(' » ');

Happy coding...


  1. Hi,

    Thanks for this walk through. Your steps are easy to follow.
    Don't quite get it to work though, echoing in step 6 doesn't render anything at all.

    Probably has to do with the code of step5. Don't quite understand where to put that.

    1. The step 5 is a supper controller class that means all your controller class must extend this controller. In that controller's init function you can place this code. If you don't have supper controller then you need to put the step 5 code in each controller's init function or preDispach function. Hope it will help you.