Currently I have the need to manipulate the content of the global navigation bar.
For now adding an item to the menu would be my main aim. The converse should be easy enough once the add has been achieved.
Could someone please take a look at the code below and offer correction / insights as to what I may be doing wrong.
<?php
// extensions/defaultExt/GlobalNavigation/Mappers/CustomNavigationMapper.php
namespace App\Extension\defaultExt\GlobalNavigation\Mappers;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
class CustomNavigationMapper
{
/**
* @var ContainerInterface
*/
protected $container;
/**
* CustomNavigationMapper constructor.
* @param ContainerInterface $container
*/
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
/**
* Event listener for kernel.request
* @param RequestEvent $event
*/
public function onKernelRequest(RequestEvent $event): void
{
if (!$event->isMainRequest()) {
return;
}
$this->mapGlobalNavigationItems();
}
private function mapGlobalNavigationItems(): void
{
// Get the global navigation service or parameter
$topMenu = $this->container->getParameter('navigation.menu.top') ?? [];
// Define your custom menu items
$customMenuItems = [
'your_custom_menu_key' => [
'label' => 'LBL_YOUR_CUSTOM_MENU',
'acl_action' => 'view',
'acl_module' => 'YourModuleName',
'icon' => 'fa-star', // Font Awesome icon
'link' => 'index.php?module=YourModuleName&action=index',
'order' => 30
],
];
// Register translations if needed
$translator = $this->container->get('translator');
if (!isset($translator->getCatalogue()->all()['messages']['LBL_YOUR_CUSTOM_MENU'])) {
$translator->getCatalogue()->set(
'LBL_YOUR_CUSTOM_MENU',
'Your Custom Menu',
'messages'
);
}
foreach ($customMenuItems as $key => $item) {
$topMenu[$key] = $item;
}
$this->container->setParameter('navigation.menu.top', $topMenu);
}
}
# extensions/defaultExt/Resources/config/services.yml
services:
extension.defaultext.global_navigation_mapper:
class: App\Extension\defaultExt\GlobalNavigation\Mappers\CustomNavigationMapper
arguments: ['@service_container']
tags:
- { name: kernel.event_listener, event: kernel.request, method: onKernelRequest, priority: 20 }