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...