I use EasyAdmin 3 in my Symfony project, the problem I have with easyAdmin is that, I have two roles, role admin and role artist. I found how it works for each one to se their own products which published but i want admin to see all of everyone's products, I mean that artists must see their own products and admin see everyone's products in easyadmin?
I will be thankfull if someone give a hand
<?php
namespace App\Controller\Admin;
use App\Entity\Product;
use Doctrine\ORM\QueryBuilder;
use EasyCorp\Bundle\EasyAdminBundle\Config\Crud;
use EasyCorp\Bundle\EasyAdminBundle\Dto\EntityDto;
use EasyCorp\Bundle\EasyAdminBundle\Dto\SearchDto;
use EasyCorp\Bundle\EasyAdminBundle\Field\SlugField;
use EasyCorp\Bundle\EasyAdminBundle\Field\TextField;
use EasyCorp\Bundle\EasyAdminBundle\Field\ImageField;
use EasyCorp\Bundle\EasyAdminBundle\Field\MoneyField;
use EasyCorp\Bundle\EasyAdminBundle\Field\BooleanField;
use EasyCorp\Bundle\EasyAdminBundle\Field\IntegerField;
use EasyCorp\Bundle\EasyAdminBundle\Field\TextEditorField;
use EasyCorp\Bundle\EasyAdminBundle\Field\AssociationField;
use EasyCorp\Bundle\EasyAdminBundle\Collection\FieldCollection;
use EasyCorp\Bundle\EasyAdminBundle\Collection\FilterCollection;
use EasyCorp\Bundle\EasyAdminBundle\Controller\AbstractCrudController;
class ProductCrudController extends AbstractCrudController
{
public static function getEntityFqcn(): string
{
return Product::class;
}
public function createIndexQueryBuilder(SearchDto $searchDto, EntityDto $entityDto, FieldCollection $fields, FilterCollection $filters): QueryBuilder
{
$user = $this->getUser()->getId();
$qb = parent::createIndexQueryBuilder($searchDto, $entityDto, $fields, $filters);
$qb->where('entity.user = :id');
$qb->setParameter('id', $user);
return $qb;
}
Thank you Hamid
Depending of the user role you'll have to add or not the where
condition on user id.
So if the user is admin, don't add the where
condition. Else, add the where
condition.
To test the user role, you can call $this->isGranted('ROLE_ADMIN')
It would be something like this :
public function createIndexQueryBuilder(SearchDto $searchDto, EntityDto $entityDto, FieldCollection $fields, FilterCollection $filters): QueryBuilder
{
$user = $this->getUser()->getId();
$qb = parent::createIndexQueryBuilder($searchDto, $entityDto, $fields, $filters);
if (!$this->isGranted('ROLE_ADMIN')) {
$qb->where('entity.user = :id');
$qb->setParameter('id', $this->getUser()->getId());
}
return $qb;
}