I have created a patch for @4k4's
answer that also uses dependency injection.
To apply this patch:
Take the code snippet below and paste it into a new file e.g test.patch
.
Then run git apply /path-to-file/test.patch
.
For a UI only solution, see my other answer.
diff --git a/core/modules/views/src/Plugin/EntityReferenceSelection/ViewsSelection.php b/core/modules/views/src/Plugin/EntityReferenceSelection/ViewsSelection.php
index 79707af..e092ba9 100644
--- a/core/modules/views/src/Plugin/EntityReferenceSelection/ViewsSelection.php
+++ b/core/modules/views/src/Plugin/EntityReferenceSelection/ViewsSelection.php
@@ -4,6 +4,7 @@
use Drupal\Core\DependencyInjection\DeprecatedServicePropertyTrait;
use Drupal\Core\Entity\EntityReferenceSelection\SelectionPluginBase;
+use Drupal\Core\Entity\EntityRepositoryInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Form\FormStateInterface;
@@ -59,6 +60,13 @@ class ViewsSelection extends SelectionPluginBase implements ContainerFactoryPlug
*/
protected $currentUser;
+ /**
+ * The entity repository.
+ *
+ * @var EntityRepositoryInterface
+ */
+ protected $entityRepository;
+
/**
* Constructs a new ViewsSelection object.
*
@@ -74,13 +82,16 @@ class ViewsSelection extends SelectionPluginBase implements ContainerFactoryPlug
* The module handler service.
* @param \Drupal\Core\Session\AccountInterface $current_user
* The current user.
+ * @param \Drupal\Core\Entity\EntityRepositoryInterface $entityRepository
+ * The entity repository.
*/
- public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager, ModuleHandlerInterface $module_handler, AccountInterface $current_user) {
+ public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager, ModuleHandlerInterface $module_handler, AccountInterface $current_user, EntityRepositoryInterface $entityRepository) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->entityTypeManager = $entity_type_manager;
$this->moduleHandler = $module_handler;
$this->currentUser = $current_user;
+ $this->entityRepository = $entityRepository;
}
/**
@@ -93,7 +104,8 @@ public static function create(ContainerInterface $container, array $configuratio
$plugin_definition,
$container->get('entity_type.manager'),
$container->get('module_handler'),
- $container->get('current_user')
+ $container->get('current_user'),
+ $container->get('entity.repository')
);
}
@@ -231,6 +243,7 @@ public function getReferenceableEntities($match = NULL, $match_operator = 'CONTA
if ($result) {
foreach ($this->view->result as $row) {
$entity = $row->_entity;
+ $entity = $this->entityRepository->getTranslationFromContext($entity);
$return[$entity->bundle()][$entity->id()] = $entity->label();
}
}