KnpMenu unable to set the current menu item

I saw other errors about this problem. I did the same. When I try to display the menu, I get this Fatal error:

Fatal error: Call to undefined method Knp\Menu\MenuItem::setCurrentUri() in ProjectBundle/Menu/Builder.php on line 23 

This is what my Builder looks like:

 <?php use Knp\Menu\FactoryInterface; use Symfony\Component\DependencyInjection\ContainerAware; use Symfony\Component\HttpFoundation\Request; class Builder extends ContainerAware { private $factory; public function __construct(FactoryInterface $factory) { $this->factory = $factory; } public function createMenu(Request $request) { $menu = $this->factory->createItem('root'); $menu->setCurrentUri($request->getRequestUri()); $menu->addChild('Home', array('route' => '_home')); $menu->addChild('About', array('route' => '_about')); $menu->addChild('Bullshit', array('route' => '_bullshit')); return $menu; } } 

I looked at the error tracker on Github and it seems this problem has been fixed, but why am I having the same problem again?

I mean, when I var_dump($menu) , it clearly says that it is a MenuItem and, seeing the KnpMenu documentation, there is definitely a setCurrentUri() method for my $menu .

+4
source share
4 answers

The MenuItem::setCurrentUri() method seems to be deprecated from version 1.1. See https://github.com/KnpLabs/KnpMenu/issues/63 for more details. There are several links on this issue on how to set the current uri in the menu using UrlVoter .

+1
source

It should not work, if the problem is related to the request, you can try the following:

  public function **CreateMenu**(\Knp\Menu\FactoryInterface $factory, array $options) { $menu = $factory->createItem('root'); $menu->setCurrentUri($this->container->get('request')->getRequestUri()); $menu->addChild('Home', array('route' => '_home')); $menu->addChild('About', array('route' => '_about')); .. return $menu;} 
+3
source

@ aurny2420289 gives a simple solution.

But now he suggested using UriVoter

 use Knp\Menu\Matcher\Voter\UriVoter; use Knp\Menu\Renderer\ListRenderer; //... $matcher = new Matcher(); $matcher->addVoter(new UriVoter($_SERVER['REQUEST_URI'])); $renderer = new ListRenderer($matcher); //... 
+2
source

I found the simplest solution. just add:

 $menu->setCurrent(true); 

It adds the current current to the current menu. The setCurrentUri method is deprecated and then removed from knpmenu.

0
source

Source: https://habr.com/ru/post/1433415/


All Articles