Home » Php » php – Knp Menu Bundle Current item Symfony 2

php – Knp Menu Bundle Current item Symfony 2

Posted by: admin July 12, 2020 Leave a comment

Questions:

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;
    }
}
How to&Answers:

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.

Answer:

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