Skip to content

Instantly share code, notes, and snippets.

@alborq
Created July 24, 2015 14:12
Show Gist options
  • Save alborq/7315e42adf899957e2b0 to your computer and use it in GitHub Desktop.
Save alborq/7315e42adf899957e2b0 to your computer and use it in GitHub Desktop.
KNPMenuBuilder, WIth Event how to order element => solution
<?php
namespace xxxx\Menu;
use Knp\Menu\FactoryInterface;
use Knp\Menu\ItemInterface;
use Symfony\Component\DependencyInjection\ContainerAware;
use xxx\Event\ConfigureMenuEvent;
class MenuBuilder extends ContainerAware
{
public function build(FactoryInterface $factory)
{
$menu = $factory->createItem('root');
$menu->addChild('Accueil', array(
'route' => 'xxxxxx',
'extras' => array(
'order' => 70 //Use step of 10 is better for add element between 2
)
));
//classic event solution
$this->container->get('event_dispatcher')->dispatch(
ConfigureMenuEvent::CONFIGURE,
new ConfigureMenuEvent($factory, $menu)
);
//damn var useless but.. uasort need a reference
$child = $menu->getChildren();
uasort($child, array($this, 'sortMenu'));
$menu->setChildren($child);
return $menu;
}
protected function sortMenu($a, $b){
/** @var ItemInterface $a */
$aOrder = $a->getExtra('order');
/** @var ItemInterface $b */
$bOrder = $b->getExtra('order');
if($aOrder === $bOrder){
return 0;
}
return ($aOrder < $bOrder) ? -1 : 1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment