2

I am using KnpMenu with Symfony2.3 through the KnpMenuBundle.

I would like to customize the class MenuItem by adding an attribute, the simplest way.

The aim is to be able to link any MenuItem to one of my application's entity, and to retrieve it afterwards.

For example, I want to do this:

$menu = $factory->createItem('root');
$menu->addChild('New Model', array('route' => 'my_route'))
     ->setAttribute('icon', 'glyphicon-plus')
     ->setRelatedEntity($myEntity);   // <== This doesn't exist by default

The easy but ugly way would be to edit Knp\Menu\MenuItem.php and add this:

/**
 * Entity to which this menuItem is related
 * @var Entity
 */
private $relatedEntity;

/**
 * Set relatedEntity
 *
 * @param string $relatedEntity
 * @return MenuItem
 */
public function setRelatedEntity($relatedEntity) {
    $this->relatedEntity = $relatedEntity;    
    return $this;
}

/**
 * Get relatedEntity
 * @return Entity 
 */
public function getRelatedEntity() {
    return $this->relatedEntity;
}

I know it isn't the proper way to do it so I tried to override Knp\Menu\MenuItem and then Knp\Menu\MenuFactory but it is not enough...

I have the feeling I have to override a lot more things, so here I come to ask advice. The bundle is quite complex and I have the feeling that this functionnality (adding class attribute to MenuItem) is already managed by the bundle, although I don't understand how.

Any idea?

Blacksad
  • 1,230
  • 1
  • 14
  • 23
  • Your question is answered here: http://stackoverflow.com/a/21312804/1354222 – 11mb Jan 13 '16 at 12:08
  • Possible duplicate of [Render custom attribute KNP Menu](http://stackoverflow.com/questions/21301710/render-custom-attribute-knp-menu) – 11mb Jan 13 '16 at 12:09

0 Answers0