I am using Sylius 1.11 and I am trying to build a custom filter based on a custom field of the native Order entity.
The field is called author
and it reference the adminUser_id. Sometimes, there is no adminUser_id so the field is null
in the database.
I want to create a multi-select filter to find orders when adminUser_id equals 2 and is null.
So, here is the filter :
<?php
declare(strict_types=1);
namespace App\Component\App\Grid\Filter;
use Sylius\Component\Grid\Data\DataSourceInterface;
use Sylius\Component\Grid\Filtering\FilterInterface;
final class MultiselectFilterAuthor implements FilterInterface
{
public function apply(DataSourceInterface $dataSource, string $name, $data, array $options): void
{
if (empty($data)) {
return;
}
$field = $options['field'] ?? $name;
$expressionBuilder = $dataSource->getExpressionBuilder();
$expressions[] = $expressionBuilder->isNull('author');
$expressions[] = $expressionBuilder->in('author.id', [2]);
$dataSource->restrict($expressionBuilder->orX(...$expressions));
}
}
If I try each expressions independently, it works.
$expressions[] = $expressionBuilder->isNull('author');
-> show only the orders with an author === null
but when I combine them, it doesn't works
I finally found out why it wasn't working...
I needed to add an author
join in the Sylius grid query builder for the Order entity :
public function createListQueryBuilder(): QueryBuilder
{
$qb = $this->createQueryBuilder('o');
return $qb
->addSelect('customer')
->leftJoin('o.customer', 'customer')
->leftJoin('o.author', 'author')
->leftJoin('customer.contacts', 'contacts')
;
}