Search code examples
phpsymfonyeasyadmin

How to add condition in AssociationField in Symfony EasyAdmin


I'm building book management system. where each books have many chapters.

When I filter the list chapter by book I want to when I create new chapter the association field book hidden or at least filtered by the current filter (book).


Solution

  • AssociationField has a method called setQueryBuilder which help you modify the query.

    In your case, your association field should look like:

    AssociationField::new('chapters')
                ->setQueryBuilder(function ($queryBuilder) {
                    return $queryBuilder->andWhere(''); // your query
    
                });
    

    You could also use a repository and call its method but returning a query builder (and not the result) inside setQueryBuilder.