Search code examples
phpzend-framework2zend-navigation

ZF2 - Active <li> in Zend Navigation Menu


I've managed to generate menu using Zend Navigation. However, the active page is never set (active class is not set for any <li> element).

My partial:

foreach ($pages as $page): ?>

<?php if (!$page->isVisible() || !$this->navigation()->menu()->accept($page)) continue; ?>

<li role="presentation" <?php if ($page->isActive()) echo 'class="active"' ?>>
    <a href="<?php echo $page->getHref() ?>">
        <?php if ($icon = $page->get('icon')) {
            echo '<span class="' . $icon . '"></span>';
        } ?>
        <span> <?php echo $this->translate($page->getLabel()) ?> </span>
    </a>
</li>

<?php endforeach ?>

Extract of module.config.php:

    'navigation' => array(
        'default' => array(
            array(
                'label' => 'Page 1',
                'route' => 'application/default',
                'namespace' => 'Application\Controller',
                'controller' => 'Index',
                'action' => 'page1',
                'icon' => 'fa fa-2x fa-file-text',
                'order' => 10,
            ),
            array(
                'label' => 'Page 2',
                'route' => 'application/default',
                'namespace' => 'Application\Controller',
                'controller' => 'Index',
                'action' => 'page2',
                'icon' => 'fa fa-2x fa-file-text',
                'order' => 20,
            ),
        ),
    ),

The menu is rendered properly on the page, but without any active class:

    $partial = array('partial/menu.phtml', 'default');
    echo $this->navigation('navigation')
        ->menu()
        ->setMinDepth(0)
        ->setMaxDepth(0)
        ->setPartial($partial);

After some research into ZF code, I've found something I don't understand (in Zend\View\Helper\Navigation\Menu.php):

// in renderNormalMenu function, line 288     
$isActive = $page->isActive(true);

Any idea or suggestion regarding my problem?

Thanks a lot,


Solution

  • Problem was in module.config.php ; the isActive method (from Zend\Navigation\Mvc) was expected the "full" controller name (including namespace).

    My config was splitting namespace and controller name, wich causes the issue.

    Solution:

                array(
                    'label' => 'Page 1',
                    'route' => 'application/default',
                    'controller' => 'Application\Controller\Index',
                    'action' => 'page1',
                    'icon' => 'fa fa-2x fa-file-text',
                    'order' => 10,
                ),