Returns matched labels based on a given field, instance and search string.
This function can be used by other modules that wish to pass a mocked definition of the field on instance.
array $field: The field array definition.
array $instance: The instance array definition.
string $entity_type: The entity type.
string $entity_id: (optional) The entity ID the entity reference field is attached to. Defaults to ''.
string $prefix: (optional) A prefix for all the keys returned by this function.
string $string: (optional) The label of the entity to query by.
array A list of matched entity labels.
\Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException Thrown when the current user doesn't have access to the specifies entity.
\Drupal\entity_reference\EntityReferenceController
public function getMatches($field, $instance, $entity_type, $entity_id = '', $prefix = '', $string = '') {
$target_type = $field['settings']['target_type'];
$matches = array();
$entity = NULL;
if ($entity_id !== 'NULL') {
$entities = $this->entityManager
->getStorageController($entity_type)
->load(array(
$entity_id,
));
$entity = reset($entities);
if (!$entity || !$entity
->access('view')) {
throw new AccessDeniedHttpException();
}
}
$handler = entity_reference_get_selection_handler($field, $instance, $entity);
if (isset($string)) {
// Get an array of matching entities.
$widget = entity_get_form_display($instance['entity_type'], $instance['bundle'], 'default')
->getComponent($instance['field_name']);
$match_operator = !empty($widget['settings']['match_operator']) ? $widget['settings']['match_operator'] : 'CONTAINS';
$entity_labels = $handler
->getReferencableEntities($string, $match_operator, 10);
// Loop through the entities and convert them into autocomplete output.
foreach ($entity_labels as $values) {
foreach ($values as $entity_id => $label) {
$key = "{$label} ({$entity_id})";
// Strip things like starting/trailing white spaces, line breaks and
// tags.
$key = preg_replace('/\\s\\s+/', ' ', str_replace("\n", '', trim(decode_entities(strip_tags($key)))));
// Names containing commas or quotes must be wrapped in quotes.
if (strpos($key, ',') !== FALSE || strpos($key, '"') !== FALSE) {
$key = '"' . str_replace('"', '""', $key) . '"';
}
$matches[$prefix . $key] = $label;
}
}
}
return $matches;
}