EasyAdmin (v2): filter list view by the property of a related entity

Viewed 909

I am willing to implement exactly the kind of list filtering that is described in EasyAdmin (v.2) documentation on Symfony (Custom dynamic filters), i.e. filtering the list view of an entity by the property of a related entity (e.g. list orders by customers of a given country).

With only the following code blocks available in the doc I am quite lost on how to create a custom EntityTypeFilter with the usual two select lists (is same/is not same list & list of available Country for Order via the Customer association). What should be in the configureOptions() and getParent() functions?

Thanks !

# config/packages/easy_admin.yaml
easy_admin:
    entities:
        Users:
            class: App\Entity\Order
            list:
                filters:
                    # 'country' doesn't exist as a property of 'Order' so it's
                    # defined as 'not mapped' to avoid errors
                    - property: 'country'
                      type: 'App\Form\Filter\CustomerCountryFilterType'
                      mapped: false
// App\Form\Filter\CustomerCountryFilterType
// ...

public function filter(QueryBuilder $queryBuilder, FormInterface $form, array $metadata)
{
    if (null !== $form->getData()) {
        $queryBuilder
            ->leftJoin('entity.customer', 'customer')
            ->andWhere('customer.country = :country')
            ->setParameter('country', $form->getData());
    }
}
1 Answers

Try this:

use Symfony\Bridge\Doctrine\Form\Type\EntityType;
// ...

public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults([
        'class' => Country::class
    ]);
}

public function getParent()
{
    return EntityType::class;
}

If you want to sort by country name, you can add a custom query builder to the options:

use Doctrine\ORM\EntityRepository;
// ...

public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults([
        'class' => Country::class,
        'query_builder' => function (EntityRepository $er) {
            return $er->createQueryBuilder('c')
            ->orderBy('c.name', 'ASC');
        }
    ]);
}
Related