Closed Hy3n4 closed 6 years ago
This is with the knpmenulistener, but same or similar applies with out
<?php
/**
* KnpMenuListener.php
* symfony3
* Date: 13.06.16
*/
namespace AppBundle\EventListener;
use Avanzu\AdminThemeBundle\Event\KnpMenuEvent;
use Symfony\Component\DependencyInjection\ContainerInterface;
class MarsKnpMenuListener
{
private $container;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
/**
* @param KnpMenuEvent $event
*/
public function onSetupKnpMenu(KnpMenuEvent $event)
{
$menu = $event->getMenu();
$factory = $event->getFactory();
$childOptions = $event->getChildOptions();
if($this->container->get('security.authorization_checker')->isGranted('ROLE_REGISTERED')) {
$menu->addChild('My Hours', ['route' => 'myhours_choose'])->setLabelAttribute('icon', 'fa fa-h-square');
$menu->addChild('My Profile', ['route' => 'fos_user_profile_show'])->setLabelAttribute('icon', 'fa fa-user');
}
if($this->container->get('security.authorization_checker')->isGranted('ROLE_SHIFT')) {
$shiftManager = $menu->addChild('Shift Manager', $childOptions)->setLabelAttribute('icon', 'fa fa-clock-o');
$shiftManager->addChild('Shifts', ['route' => 'shift_hours'])->setLabelAttribute('icon', 'fa fa-clock-o');
$shiftManager->addChild('Approve', ['route' => 'shift_worked'])->setLabelAttribute('icon', 'fa fa-check');
}
if($this->container->get('security.authorization_checker')->isGranted('ROLE_ADMIN')) {
$Admin = $menu->addChild('Admin', $childOptions)->setLabelAttribute('icon', 'fa fa-users');
$Admin->addChild('Permissions', ['route' => 'admin_users'])->setLabelAttribute('icon', 'fa fa-lock');
$Admin->addChild('Hours', ['route' => 'admin_hours'])->setLabelAttribute('icon', 'fa fa-clock-o');
}
}
}
and the service
app.knp_menu_listener:
class: AppBundle\EventListener\MarsKnpMenuListener
arguments: ['@service_container']
tags:
- { name: kernel.event_listener, event: theme.sidebar_setup_knp_menu, method: onSetupKnpMenu }
@hounded thank you sir very much. That was exactly what I needed. I just did not know how to get container to Listener. Thank you for enlightenment.
Hi, is it possible to have different Sidebar menu for different user roles? Let's say I have Admin user with role SUPER_ADMIN_ROLE and I want to have extra items in sidebar menu just for SUPER_ADMIN_ROLE. But I don't want ADMIN_ROLE users to see those items.
Is it possible? I tried to $this->getUser() in SidebarLestener to filter it by standard if() but it seems to not work this way. Please be advised I am not so much experienced Symfony developer. I am using trial and error style to achieve goals in my project :)
Also, this project seems to be a bit abandoned, isn't it?
Thanks everyone for any hint.
Patrik