Question

I have extended SonataUserBundle and I'd like to customize the Admin query to restrict the list:

class UserAdmin extends BaseUserAdmin
{
// ...
    public function createQuery($context = 'list')
    {
        $query = parent::createQuery($context);
        $query->andWhere( 
            $query->expr()->eq($query->getRootAlias().'.company', ':comp')
        );
        $query->setParameter('comp', $securityContext->user->getCompany());
        return $query;
    }
// ...
}

Here, I'm trying to make the user only see users from his company.
But $securityContext is not set.

Can someone tell how to inject the security context into my admin class ?

Was it helpful?

Solution

You have to inject the security context service in your UserAdmin service.

In order to do that, you have to update the services.yml of your bundle:

services:
    # ...
    sonata.admin.user:
        class: My\ProjectBundle\Admin\UserAdmin
        tags:
            - {name: sonata.admin, manager_type: orm, group: users, label: users}
        arguments:
            - null
            - Application\Sonata\UserBundle\Entity\User
            - SonataAdminBundle:CRUD
            - @security.context #forth argument
        calls:
            - [setTranslationDomain, [MyProjectBundle]]
            - [setUserManager, [@fos_user.user_manager]]

In you UserAdmin class, override the constructor:

namespace My\ProjectBundle\Admin;

class UserAdmin extends Admin
{

    private $securityContext = null;

    public function __construct($code, $class, $baseControllerName, $secutiryContext=null)
    {
        parent::__construct($code, $class, $baseControllerName);
        $this->securityContext = $securityContext;
    }

    public function createQuery($context = 'list')
    {
        $query = parent::createQuery($context);
        $query->andWhere( 
            $query->expr()->eq($query->getRootAlias().'.company', ':comp')
        );
        $query->setParameter('comp', $this->securityContext->user->getCompany());
        return $query;
    }
}

I didn't test this code, but i use this method to inject service_container in sonata admin to manage file upload using Gedmo Uploadable.

Hope this helps.

OTHER TIPS

I know this is a very old question, but what about;

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

first thing in public function createQuery($context = 'list') {

and then at setParameter you can just use $user->getCompany()

Like this;

public function createQuery($context = 'list')
{
    $user = $this->getConfigurationPool()->getContainer()->get('security.context')->getToken()->getUser();

    $query = parent::createQuery($context);
    $query->andWhere( 
        $query->expr()->eq($query->getRootAlias().'.company', ':comp')
    );
    $query->setParameter('comp', $user->getCompany());
    return $query;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top