[Symfony] Use a custom query builder in YAML with the EasyAdmin bundle to configure entities widgets

Published on 2019-05-07 • Modified on 2019-05-07

When editing an entity with the EasyAdmin bundle and having relations to other entities, sometimes you don't want to display all possible related rows but you want to filter the allowed entites to be selected. This can be done throught the query_builder option of the entity type. You can pass a static function of the target entity repository: this function will automatically receive as the first argument the repository service of the entity. In this example we exclude entities having an expired start date.

# app/config/easy_admin.yml
    # ...
            class: EventBundle\Entity\Activity
                    - { property: 'event', type: 'entity', type_options: { class: 'EventBundle\Entity\Event', required: true, multiple: false, query_builder: 'EventBundle\Entity\EventRepository::adminQueryBuilderForFeEvents' }, css_class: 'col-sm-6' }


// src/EventBundle/Entity/EventRepository.php

use Doctrine\ORM\QueryBuilder;

 * Admin filter: don't display past events.
public static function adminQueryBuilderForFeEvents(EventRepository $r): QueryBuilder
    return $r->createQueryBuilder('e')
       ->innerJoin('e.eventType', 'et')
       ->where('et.id = :event_type')
       ->setParameter('event_type', 1)
       ->andWhere('e.startDate > :now')
       ->setParameter('now', date_create())
       ->orderBy('e.id', 'DESC');

 More on Stackoverflow  Random snippet

  Work with me!