KnpMenuBundle, keep Main Menu active even for sub actions

2.4k views Asked by At

my question is related to the following, is this the "proper" way or is there a better solution ?

Symfony2 KnpMenuBundle: set active a menu item even when its not on that menu

Thats my current code:

public function mainMenu(FactoryInterface $factory, array $options)
{
    $menu = $factory->createItem('root');
    $menu->setChildrenAttributes(array('class' => 'nav navbar-nav'));
    $menu->addChild('Home',
        array('route' => 'home'
    ));
    $menu->addChild('Producers',
        array(
        'route' => 'producers_show'
    ));
    $menu->addChild('Ships',
        array(
            'route' => 'ships_show'
        ));

    /* not working */
       $request = $this->container->get('request');
       $routeName = $request->get('_route');
       switch ($routeName)
       {

           case 'producer_create':
           case 'ship_create':
                 $menu->setCurrent(true);
           break;
       }

    return $menu;
}

The Rendered HTML Looks like the following for the route "ship/create"

<ul class="nav navbar-nav">
    <li class="first">        
        <a href="/app_dev.php/">Home</a>        
    </li>
    <li>        
         <a href="/app_dev.php/producers">Producers</a>        
    </li>
    <li class="last">        
         <a href="/app_dev.php/ships">Ships</a>        
    </li>
</ul>

As you can see, nothing is set 'active' Do I have to add the sub actions such as create update delete to the Menu either, and hide them ?? How do I solve this issue please?

1

There are 1 answers

1
Dovydas Bartkevičius On BEST ANSWER

The problem with your code is that you're setting the root $menu item as current every time.

switch (true)
{
    case preg_match('/^producer(s)?_/', $routeName):
        // setting Producers as the current
        $menu->getChild('Producers')->setCurrent(true);
        break;

    case preg_match('/^ship(s)?_/', $routeName):
        // setting Ships as the current
        $menu->getChild('Ships')->setCurrent(true);
        break;

    default:
        $menu->setCurrent(true);
}