3 namespace Drupal\Core\Entity;
5 use Drupal\Component\Utility\Html;
6 use Drupal\Component\Utility\Tags;
7 use Drupal\Core\Entity\EntityReferenceSelection\SelectionPluginManagerInterface;
10 * Matcher class to get autocompletion results for entity reference.
12 class EntityAutocompleteMatcher {
15 * The entity reference selection handler plugin manager.
17 * @var \Drupal\Core\Entity\EntityReferenceSelection\SelectionPluginManagerInterface
19 protected $selectionManager;
22 * Constructs a EntityAutocompleteMatcher object.
24 * @param \Drupal\Core\Entity\EntityReferenceSelection\SelectionPluginManagerInterface $selection_manager
25 * The entity reference selection handler plugin manager.
27 public function __construct(SelectionPluginManagerInterface $selection_manager) {
28 $this->selectionManager = $selection_manager;
32 * Gets matched labels based on a given search string.
34 * @param string $target_type
35 * The ID of the target entity type.
36 * @param string $selection_handler
37 * The plugin ID of the entity reference selection handler.
38 * @param array $selection_settings
39 * An array of settings that will be passed to the selection handler.
40 * @param string $string
41 * (optional) The label of the entity to query by.
44 * An array of matched entity labels, in the format required by the AJAX
45 * autocomplete API (e.g. array('value' => $value, 'label' => $label)).
47 * @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
48 * Thrown when the current user doesn't have access to the specified entity.
50 * @see \Drupal\system\Controller\EntityAutocompleteController
52 public function getMatches($target_type, $selection_handler, $selection_settings, $string = '') {
56 'target_type' => $target_type,
57 'handler' => $selection_handler,
58 'handler_settings' => $selection_settings,
60 $handler = $this->selectionManager->getInstance($options);
63 // Get an array of matching entities.
64 $match_operator = !empty($selection_settings['match_operator']) ? $selection_settings['match_operator'] : 'CONTAINS';
65 $entity_labels = $handler->getReferenceableEntities($string, $match_operator, 10);
67 // Loop through the entities and convert them into autocomplete output.
68 foreach ($entity_labels as $values) {
69 foreach ($values as $entity_id => $label) {
70 $key = "$label ($entity_id)";
71 // Strip things like starting/trailing white spaces, line breaks and
73 $key = preg_replace('/\s\s+/', ' ', str_replace("\n", '', trim(Html::decodeEntities(strip_tags($key)))));
74 // Names containing commas or quotes must be wrapped in quotes.
75 $key = Tags::encode($key);
76 $matches[] = ['value' => $key, 'label' => $label];