Zend Framework 2 navigation menu to array dehydration view helper

Sometimes you need to customize Zend Framework navigation menu output. For instance change <ul><li> output to <div><span>. This is impossible with Zend\View\Helper\Navigation\Menu because its HTML output isn't much customizable (only things like class, indent etc.). Such customization is possible with "partial" script, but my solution is to write a view helper that utilizes navigation menu to array dehydration.

Helper:

<?php
//<YOUR_MODULE>/View/Helper/NavigationMenuDehydrate.php
namespace <YOUR_MODULE>\View\Helper;

use Zend\View\Helper\AbstractHelper;
use RecursiveIteratorIterator;

class NavigationMenuDehydrate extends AbstractHelper
{
    
    protected $container;
    
    public function __invoke($container = null)
    {
        $this->container = $container;
        return $this;
    }
    
    public function dehydrate()
    {
        $array = array();
        $iterator = new RecursiveIteratorIterator($this->getView()
        ->navigation($this->container)->getContainer(), RecursiveIteratorIterator::SELF_FIRST);
        foreach ($iterator as $entry) {
            //TODO depth support
            $params = array(
                    'isActive' => $entry->isActive(true),
                    'label' => $entry->getLabel(),
                    'href' => $entry->getHref(),
            );
            $array[] = $params;
        }
        return $array;
    }
    
}

Add to your module config:

    'view_helpers' => array(
        'invokables' => array(
            'navigationmenudehydrate' => '<YOUR_MODULE>\View\Helper\NavigationMenuDehydrate' 
        )
    )

Use in your template like this:

foreach ($this->navigationMenuDehydrate('navigation')->dehydrate() as $entry) ...

Comments

  1. May I point developers interested in learning ZF2 to my recently released book "Web Development with Zend Framework 2" (https://leanpub.com/zendframework2-en)? This may be of help to get you started and is available for instant download for only a few bucks. Thanks!

    ReplyDelete
  2. Thanks for helping keep us on track. I like this and your other posts too.

    ReplyDelete

Post a Comment

Popular posts from this blog

Memory efficient array permutation in PHP 5.5 using generators

How to dump http request headers with PHP under CGI/FastCGI SAPI

Zend Framework 2 AJAX: return JSON response from controller action. The proper way.