Sonata Admin Bundle dashboard filter entity from role and DDBB permissions Sonata Admin Bundle dashboard filter entity from role and DDBB permissions symfony symfony

Sonata Admin Bundle dashboard filter entity from role and DDBB permissions


The easiest way is to edit the query and check the access in edit/show actions.

Something like this:

Admin class

/** * {@inheritdoc} */public function createQuery($context = 'list'){    $user = $this->getConfigurationPool()->getContainer()->get('security.context')->getToken()->getUser();    /** @var \Sonata\DoctrineORMAdminBundle\Datagrid\ProxyQuery @query */    $query = $this->getModelManager()->createQuery($this->getClass(), 'o');    if (!$this->isGranted('MASTER')) {        $query            ->where('entity.user = :user')            ->setParameter('user', $user)        ;    }    return $query;}

If the user is not MASTER he will only see his own entities.

You can also implement hasSubjectAccess method of the admin class like:

/** * Check whether the user has access to the subject * * @return bool */protected function hasSubjectAccess(){    $user = $this->getConfigurationPool()->getContainer()->get('security.context')->getToken()->getUser();    if (!$this->isGranted('MASTER') && $this->getSubject()->getUser() !== $user) {        return false;    }    return true;}

and perform this kind of check in edit and show forms:

/** * {@inheritdoc} */protected function configureFormFields(FormMapper $formMapper){    if (!$this->hasSubjectAccess()) {        throw new AccessDeniedException();    }    // ...}

The other way is to implement ACL. You can read more about that in the official documentation


Finally, I get it like this:

public function createQuery($context = 'list')    $query = $this->getModelManager()->createQuery($this->getClass(), 'entity');     if ( ($this->getClass() instanceof \Sademer\CoreBundle\Entity\Resource)     || ( is_subclass_of($this->getClass(), \Sademer\CoreBundle\Entity\Resource') ) )    {          $query->select ('e');          $query->from($this->getClass(), 'e');          $query->from('CoreBundle\Entity\Resource', 'r');          $query->where('e.id = r.id AND r.company = :company');          $query->setParameter('company', 5);    }}


For me the createQuery() function didn't work. May be be due to the version of Sonata Admin. Anyways, what worked for me was configureDatagridFilters() function.

It does the same job as createQuery and looks something like this:

protected function configureDatagridFilters(DatagridMapper $datagridMapper){    $qb = $datagridMapper        ->getDatagrid()        ->getQuery()        ->getQueryBuilder();    $qb->andWhere(        // Your where clause here    );    $qb->setParameter(); // Set Parameter}