DEV Community

Jonathan McLaughlin
Jonathan McLaughlin

Posted on

Drupal: Custom EntityReferenceSelection plugin to solve issue with new EntityReference views filter.

I'm a big fan of the work going on at https://www.drupal.org/project/drupal/issues/3347343.

This issue is attempting to add a new Views filter to core that will treat any entity reference field the same way a taxonomy term reference field is treated. Specifically, you will be able to use a select dropdown or autocomplete exposed filter on any of your entity reference fields.

I have been successfully using various versions of this patch in production for a while now (I believe, starting with Drupal 9.3.x). Unfortunately, now I am building a number of custom entities that do not have bundles and there appears to be a possible issue for "bundle-less" entities:
https://www.drupal.org/project/drupal/issues/3347343#comment-15048501

My simple workaround is a custom EntityReferenceSelection plugin that comes out like this:

<?php

namespace Drupal\my_module\Plugin\EntityReferenceSelection;

use Drupal\Core\Entity\Annotation\EntityReferenceSelection;
use Drupal\Core\Entity\Plugin\EntityReferenceSelection\DefaultSelection;

/**
 *
 * @EntityReferenceSelection(
 *   id = "bundleless_selection",
 *   group = "bundleless_selection",
 *   label = @Translation("Bundle-less Entity Selection"),
 *   weight = 0,
 *   entity_types = { }
 * )
 */
class BundlelessSelection extends DefaultSelection {

  /**
   * @inheritDoc
   */
  protected function buildEntityQuery($match = NULL, $match_operator = 'CONTAINS') {
    $configuration = $this->getConfiguration();
    $target_type = $configuration['target_type'];
    $entity_type = $this->entityTypeManager->getDefinition($target_type);

    // For entities without bundles, $this->configuration['target_bundles']
    // will likely be an empty array, but according to comments in
    // DefaultSelection, it should be NULL.    
    if (empty($entity_type->getKey('bundle'))) {
      $this->configuration['target_bundles'] = NULL;
    }

    return parent::buildEntityQuery($match, $match_operator);
  }

}
Enter fullscreen mode Exit fullscreen mode

Note: There appears to be an issue with the discovery of EntityReferenceSelection plugins. Always make the group and id properties match. (https://www.drupal.org/project/drupal/issues/2649712)

Top comments (0)