Didatus
Didatus

Reputation: 900

How to set menuIndex properly in EasyAdmin AdminUrlGenerator?

Within EasyAdmin for Symfony you can use the AdminUrlGenerator for easily generating URLs to for example EasyAdmin CRUD Controllers.

Documentation here: https://symfony.com/doc/current/EasyAdminBundle/crud.html#generating-admin-urls

In my case i want to generate an URL to CRUD controller which is also linked within the Dashboard. If i create a link to a CRUD controller, the link works, but the corresponding MenuItem is not highlighted. I found out, that EasyAdmin highlights the MenuItem with an URL parameter calling menuIndex. I can unset the menuIndex during Link Generation, but then no menuItem is highlightd in the menu.

I havn't found any information on how to get the correct menuIndex for a generated CRUD URL.

So how can i generate Admin URLs with correct menuIndex?

Upvotes: 0

Views: 1111

Answers (1)

Didatus
Didatus

Reputation: 900

I want to give one possible answer. But to be honest, i don't really like my solution. Maybe someone has a better solution.

So, i am iterating over the configured menuItems within the DashboardController and trying to determine the menuIndex for a given Entity.

The code lookes like this:

private function getIndexLinkForCrudController(string $controller): string
{
    return $this->adminUrlGenerator
        ->unsetAll()
        ->setController($controller)
        ->setAction(Action::INDEX)
        ->set('menuIndex', $this->determineMenuIndexForEntity($controller::getEntityFqcn()))
        ->generateUrl();
}

private function determineMenuIndexForEntity(string $entity): ?int
{
    $menuItems = $this->configureMenuItems();

    foreach ($menuItems as $id => $menuItem) {
        /* @var MenuItemInterface $menuItem */
        $routeParameter = $menuItem->getAsDto()->getRouteParameters();
        if (
            is_array($routeParameter) &&
            array_key_exists(EA::ENTITY_FQCN, $routeParameter) &&
            $routeParameter[EA::ENTITY_FQCN] == $entity
        ) {
            return $id;
        }
    }

    return null;
}

This code works for me. But this code only works within the DashboardController. If i want to create Admin URLs within a CRUD controller i need to move the menu config to a static method and accessing it there. Also i am not fetching the error case when i cannot determine the menuIndex and returning null. For my case it's fine.

Maybe this is helpfull for someone. If somebody has better solution, i would be happy to here about it.

Upvotes: 0

Related Questions