EasyAdmin: Set menu items automatically active

EasyAdmin is a great Symfony bundle for creating administration backends. But one drawback that was always annoying me is that you always have to tell the navigation menu which items should be active. This is only possible by passing the “menuIndex” and “submenuIndex” parameters in the URL. If you want to set a manual link to a specific view or entity you always have to activate the corresponding menu items manually.

My old solution to this was to hard code the URLs in the entity including the menu indexes:

/**
*
@return string
*/
public function getProductEditLink(): string
{
return sprintf('/?entity=ProductEntity&action=edit&menuIndex=2&submenuIndex=1&id=%s', $this->getId());
}

For sure these URLs have to be adjusted whenever something is changed in the menu.

Now I created a replacement for the menu template which will automatically set the menu items active depending on the entity you are working on. As long as the “entity” parameter in the URL is present and there is a matching menu or submenu item, it will be set to active automatically. The native EasyAdmin behaviour is still working.

To override the menu template, you have to put it here (Symfony 4):

/templates/bundles/EasyAdminBundle/default/menu.html.twig