Drupal - Need to override single Drupal 8 plugin function

Method #1 You can simply create new plugin which extends class of target Core plugin.

File: modules/example/src/Plugin/EntityReferenceSelection/ExampleSelection.php

namespace Drupal\example\Plugin\EntityReferenceSelection;

use Drupal\Component\Utility\Html;
use Drupal\Core\Entity\Plugin\EntityReferenceSelection\DefaultSelection;

/**
 * Entity Reference Selection with distinguishing field.
 *
 * @EntityReferenceSelection(
 *   id = "example",
 *   label = @Translation("Example"),
 *   group = "example",
 * )
 */
class ExampleSelection extends DefaultSelection {

  /**
   * {@inheritdoc}
   */
  public function getReferenceableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 0) {
    $target_type = $this->configuration['target_type'];

    $query = $this->buildEntityQuery($match, $match_operator);
    if ($limit > 0) {
      $query->range(0, $limit);
    }

    $result = $query->execute();

    if (empty($result)) {
      return [];
    }

    $options = array();
    $entities = $this->entityManager->getStorage($target_type)->loadMultiple($result);
    foreach ($entities as $entity_id => $entity) {
      $bundle = $entity->bundle();

      $translated_entity = $this->entityManager->getTranslationFromContext($entity);
      $label = $translated_entity->label();
      $distinguishing_field = $translated_entity->get('field_example')->get(0);
      if ($distinguishing_field) {
        $label .= ' [' . $distinguishing_field->getValue()['value'] . ']';
      }
      $options[$bundle][$entity_id] = Html::escape($label);
    }

    return $options;
  }

}

Having this done navigate to field settings page and enable your reference method.

Method #2 For select list widget you can install Entity Reference Views Select which allows to build selection options using Views fields.

Method #3 Content Browser module (not stable yet) offers more advanced way to select entities.

Method #4 You may globally override Entity::label() method for required entity type. So that the [title] - [other_distinguishing_field] pattern will be used everywhere including default entity reference selection plugin.

Tags:

Plugins