Sylius Grid: Filter data for user
The Sylius Grid Bundle allows you to integrate data grids in your application with minimal configuration quickly.
By default, the Grid bundle is not aware of the currently logged-in user or any other "static" filters that you want to apply to limit the dataset that should be displayed globally.
Luckily the Grid configuration allows you to define the method of your resource's repository class used to build the database query. The only requirement: The custom method needs to return a \Doctrine\ORM\QueryBuilder
instance, e.g:
<?php
declare(strict_types=1);
namespace App\Repository;
use App\Entity\Customer\Customer;
use App\Entity\MyEntity;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\QueryBuilder;
use Sylius\Bundle\ResourceBundle\Doctrine\ORM\EntityRepository;
class MyEntityRepository extends EntityRepository
{
public function __construct(EntityManagerInterface $em)
{
parent::__construct($em, new ClassMetadata(MyEntity::class));
}
public function createQueryBuilderWithCustomerFilter(int $customerId): QueryBuilder
{
return $this->createQueryBuilder('o')
->innerJoin('o.customer', 'customer')
->andWhere('customer.id = :customerId')
->setParameter('customerId', $customerId);
}
}
As you can see, in the createQueryBuilderWithCustomerFilter,
we manually add a customer filter that the Grid bundle will take into account when querying the entities from the database.
In the Grid configuration, the custom query method needs to be configured via the setRepositoryMethod()
of the GridBuilder
instance like this:
<?php
declare(strict_types=1);
namespace App\Grid;
use App\Context\CustomerContext;
use App\Entity\MyEntity;
use Sylius\Bundle\GridBundle\Builder\GridBuilderInterface;
use Sylius\Bundle\GridBundle\Grid\AbstractGrid;
use Sylius\Bundle\GridBundle\Grid\ResourceAwareGridInterface;
class SchufaMyEntityGrid extends AbstractGrid implements ResourceAwareGridInterface
{
public function __construct(private readonly CustomerContext $customerContext)
{
}
public static function getName(): string
{
return 'app_myentity';
}
public function buildGrid(GridBuilderInterface $gridBuilder): void
{
$customer = $this->customerContext->getCustomer();
// $gridBuilder configuration here...
$gridBuilder->setRepositoryMethod('createQueryBuilderWithCustomerFilter', [$customer->getId()]);
}
public function getResourceClass(): string
{
return MyEntity::class;
}
}
As you can see, the Sylius Grid bundle is a powerful component that makes it easy to configure grids in your application and offers enough extension points to add custom functionality (e.g., custom filters).