symfonyfosuserbundlesonata-admin

Symfony2: SonataAdminBundle - How can i get the object representing the current user inside an admin class?


I use the sonata-admin bundle. I have the relationship with the user (FOSUserBundle) in the PageEntity. I want to save the current user which create or change a page.

My guess is get the user object in postUpdate and postPersist methods of the admin class and this object transmit in setUser method.

But how to realize this?

On the google's group I saw

    public function setSecurityContext($securityContext) {
        $this->securityContext = $securityContext;
    }

    public function getSecurityContext() {
        return $this->securityContext;
    }

    public function prePersist($article) {
        $user = $this->getSecurityContext()->getToken()->getUser();

        $appunto->setOperatore($user->getUsername());
    }

but this doesn't work


Solution

  • In the admin class you can get the current logged in user like this:

    $this->getConfigurationPool()->getContainer()->get('security.token_storage')->getToken()->getUser()
    

    EDIT based on feedback

    And you are doing it this? Because this should work.

     /**
         * {@inheritdoc}
         */
        public function prePersist($object)
        {
    
    $user = $this->getConfigurationPool()->getContainer()->get('security.token_storage')->getToken()->getUser();
            $object->setUser($user);
        }
    
        /**
         * {@inheritdoc}
         */
        public function preUpdate($object)
        {
    $user = $this->getConfigurationPool()->getContainer()->get('security.token_storage')->getToken()->getUser();
            $object->setUser($user);
        }