8

I have a question regarding rendering the KnpMenu Bundle for Symfony2. From I've read, there should be a "current" class at the matched route item. I've read the Knp documentation and they're saying something about RouteVoter but I can't make it working. Any ideas?

Builder code:

<?php
// src/Acme/DemoBundle/Menu/Builder.php
namespace Acme\DemoBundle\Menu;

use Knp\Menu\FactoryInterface;
use Symfony\Component\DependencyInjection\ContainerAware;

class Builder extends ContainerAware
{
    public function mainMenu(FactoryInterface $factory, array $options)
    {
        $menu = $factory->createItem('root');

        $menu->addChild('Home', array('route' => 'index'));
        $menu->addChild('About Me', array('route' => 'products'));

        return $menu;
    }
}
j0k
  • 22,600
  • 28
  • 79
  • 90
acid
  • 2,099
  • 4
  • 28
  • 41

2 Answers2

5

It's 10 months on and I followed the solution outlined above, however I found it to be convoluted. I use the following method.

class Builder extends ContainerAware
{
    public function mainMenu(FactoryInterface $factory, array $options)
    {
        $menu = $factory->createItem('root');
        // Manually set the current URI.
        $menu->setCurrentUri($this->container->get('request')->getRequestUri());
        // ... 
    }
}

I've turned a blind eye to semantics, but what wrong with an approach like the above code sample? Please provide feedback as required.

Aries
  • 744
  • 5
  • 13
  • Thanks for the workaround. I've been looking for something like this. I hope, one day, the KnpMenuBundle 2.x would be stable and we would be able to use the voters. – Nikola Petkanski Jun 19 '13 at 08:25
  • Following the guide of KnpMenuBundle for using the menu as service, the container is not longer needed. You can get the request by scoping the service to the request scope. – Nikola Petkanski Jun 19 '13 at 13:26
  • It is worth mentioning that this workaround fails in some cases. For example, when using pagination. – Nikola Petkanski Jun 21 '13 at 12:15
  • @NikolaPetkanski is there a solution to add the ``current`` class to the active page link? or should we still use this workaround above? – tirenweb Apr 14 '14 at 11:36
  • Back in the days I was unable to find a working solution, so I ended up implementing my own method for setting the active menu item. What I basically did was to use consistent naming of the routes and string compare the name of current route. Currently there's a alpha tag for the knpmenu bundle 2.0 - you can try that one. – Nikola Petkanski Apr 14 '14 at 12:08
4

Okay, apparently this solution seems to be working: https://github.com/KnpLabs/KnpMenuBundle/issues/122#issuecomment-6563863

acid
  • 2,099
  • 4
  • 28
  • 41