- 🇺🇸United States Amerie
We are using an entity autocomplete field in a custom form (not an entity edit form) and I couldn't find any info about how to use the views selection plugin in that situation so we just created our own selection plugin that extends the default one. Here it is in case anyone else needs it:
<?php namespace Drupal\YOUR_MODULE\Plugin\EntityReferenceSelection; use Drupal\Component\Utility\Html; use Drupal\Core\Entity\EntityReferenceSelection\SelectionWithAutocreateInterface; use Drupal\Core\Entity\Plugin\EntityReferenceSelection\DefaultSelection; use Drupal\Core\Field\EntityReferenceFieldItemListInterface; /** * Custom plugin implementation of the Entity Reference Selection plugin. * * @EntityReferenceSelection( * id = "default_with_bundle", * label = @Translation("Default (with entity bundle)"), * group = "default", * weight = 0, * deriver = "Drupal\Core\Entity\Plugin\Derivative\DefaultSelectionDeriver" * ) */ class DefaultWithBundleSelection extends DefaultSelection implements SelectionWithAutocreateInterface { /** * {@inheritdoc} */ public function getReferenceableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 0) { $target_type = $this->getConfiguration()['target_type']; $query = $this->buildEntityQuery($match, $match_operator); if ($limit > 0) { $query->range(0, $limit); } $result = $query->execute(); if (empty($result)) { return []; } $options = []; $entities = $this->entityTypeManager->getStorage($target_type)->loadMultiple($result); foreach ($entities as $entity_id => $entity) { $bundle = $entity->bundle(); $entity_label = $this->entityRepository->getTranslationFromContext($entity)->label() ?? ''; $bundle_label = $this->getBundleLabel($entity); $options[$bundle][$entity_id] = Html::escape($entity_label . ' [' . $bundle_label . ']'); } return $options; } private function getBundleLabel($entity) { $label = ''; if ($entity) { if ($bundle_field_name = $entity->getEntityType()->getKey('bundle')) { $bundle_field = $entity->get($bundle_field_name); if ($bundle_field instanceof EntityReferenceFieldItemListInterface) { $label = $bundle_field->entity->label(); } else { $lable = $entity->bundle(); } } } return $label; } }