EntityReferenceSelection
is a plugin type in Drupal that provides the user interface and functionality for selecting entities to reference. This plugin is used by Entity Reference fields to provide a list of entities that can be referenced.
We basically have the following referencing methods (EntityReferenceSelection
plugin) available for the entity type.
- Default (
NodeSelection
): This is the default referencing method for any entity type. It provides basic functionality to associate one entity with another entity. - Views: Filter by an entity reference view: This method requires creating an Entity Reference View. It allows for more complex referencing and filtering of entities, and can help solve most of the referencing challenges.
Drupal provides developers with the flexibility to develop their own EntityReferenceSelection
plugins. In this gist, we will develop a simple custom EntityReferenceSelection plugin by extending the NodeSelection
plugin. This will demonstrate how developers can create their own EntityReferenceSelection
plugins.
<?php
namespace Drupal\littlespoiler_base\Plugin\EntityReferenceSelection;
use Drupal\node\Plugin\EntityReferenceSelection\NodeSelection;
/**
* Allow searching entity by node id as well as label.
*
* @EntityReferenceSelection(
* id = "ext_node_selection",
* label = @Translation("Extended Node selection"),
* entity_types = {"node"},
* group = "ext_node_selection",
* weight = 2,
* deriver = "Drupal\Core\Entity\Plugin\Derivative\DefaultSelectionDeriver"
* )
*/
class ExtendedNodeSelection extends NodeSelection {
/**
* {@inheritdoc}
*/
protected function buildEntityQuery($match = NULL, $match_operator = 'CONTAINS') {
$configuration = $this->getConfiguration();
$target_type = $configuration['target_type'];
$entity_type = $this->entityTypeManager->getDefinition($target_type);
$label_key = $entity_type->getKey('label');
$id_key = $entity_type->getKey('id');
// Prevent DefaultSelection::buildEntityQuery from adding a label condition.
// Instead, add an OR condition group for label and nid.
if ($match && $id_key && $label_key) {
$query = parent::buildEntityQuery(NULL, $match_operator);
$group = $query->orConditionGroup()
->condition($label_key, $match, $match_operator)
->condition($id_key, $match);
$query->condition($group);
return $query;
}
return parent::buildEntityQuery($match, $match_operator);
}
}
It is important to add a driver to an annotation. Without a driver, the plugin will not be visible in the backend. https://drupal.stackexchange.com/a/298108/75763
Backend UI