Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

knpmenubundle: How to get user data in builder?

How can I get User data in theKnpMenuBundle's Builder?

I know I can get the user data via this line in Controller:

$user = $this->get('security.context')->getToken()->getUser();

but I want it to get in my menu builder aswell, so I can put the username in the menu.

like image 634
NaGeL182 Avatar asked Feb 07 '13 15:02

NaGeL182


People also ask

How do I enable knpmenubundle?

KnpMenuBundle should be automatically enabled and configured, thanks to Flex. If you don't use Flex, you can manually enable it, by adding the following line in your project's Kernel:

How do I create a menu in KNP?

To create a menu, first create a new class in the Menu directory of one of your bundles. This class - called Builder in our example - will have one method for each menu that you need to build. With the standard knp_menu.html.twig template and your current page being 'Home', your menu would render with the following markup:

How do I render a KNP_menu in a service container?

With the standard knp_menu.html.twig template and your current page being 'Home', your menu would render with the following markup: You only need to implement ContainerAwareInterface if you need the service container. The more elegant way to handle your dependencies is to inject them in the constructor. If you want to do that, see the method below.

What is a data resource in UI builder?

A Data Resource in UI Builder allows you to fetch data from the instance to the page and then consume that data from a component. Previous to the Quebec release, component authors had to hard code REST or GraphQL queries as well as any data transformations into their components. Blog Home MVPs


2 Answers

Your MenuBuilder is defined as a service in Symfony2, as you can see in https://github.com/KnpLabs/KnpMenuBundle/blob/master/Resources/doc/menu_service.rst

Basically, all you need to do is configure your MenuBuilder service definition to inject the security context. (http://symfony.com/doc/current/book/service_container.html#referencing-injecting-services)

like image 65
simshaun Avatar answered Sep 22 '22 20:09

simshaun


Simshaun is totaly right. After some research i manage to do it like this :

  1. Add the injection on services.yml :

    administration_main.menu.main:
      class: Knp\Menu\MenuItem
      factory_service: administration_main.menu_builder
      factory_method: createAdministrationMainMenu
      arguments: ["@request","@security.context"]
      scope: request
      tags:
          - { name: knp_menu.menu, alias: administrationMain }
    
  2. Use it on the menu builder

    use Symfony\Component\Security\Core\SecurityContext;
    
    public function createAdministrationMainMenu(Request $request, SecurityContext $securityContext){
    
      $securityContext->getToken()->getUser();
    
    }
    
like image 24
emottet Avatar answered Sep 21 '22 20:09

emottet