protected function RealnameAutocompleteController::getMatches in Real Name 8
Same name and namespace in other branches
- 2.x src/Controller/RealnameAutocompleteController.php \Drupal\realname\Controller\RealnameAutocompleteController::getMatches()
Gets matched labels based on a given search string.
Parameters
array $selection_settings: An array of settings that will be passed to the selection handler.
string $string: (optional) The label of the entity to query by.
Return value
array An array of matched entity labels, in the format required by the AJAX autocomplete API (e.g. array('value' => $value, 'label' => $label)).
Throws
\Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException Thrown when the current user doesn't have access to the specified entity.
1 call to RealnameAutocompleteController::getMatches()
- RealnameAutocompleteController::handleAutocomplete in src/
Controller/ RealnameAutocompleteController.php - Autocomplete the label of an entity.
File
- src/
Controller/ RealnameAutocompleteController.php, line 64
Class
- RealnameAutocompleteController
- Defines a route controller for entity autocomplete form elements.
Namespace
Drupal\realname\ControllerCode
protected function getMatches(array $selection_settings, $string = '') {
$matches = [];
if (isset($string)) {
// Get an array of matching entities.
$match_operator = !empty($selection_settings['match_operator']) ? $selection_settings['match_operator'] : 'CONTAINS';
$include_anonymous = isset($selection_settings['include_anonymous']) ? $selection_settings['include_anonymous'] : TRUE;
$connection = \Drupal::database();
$query = $connection
->select('users_field_data', 'u');
$query
->fields('u', [
'uid',
]);
$query
->leftJoin('realname', 'rn', 'u.uid = rn.uid');
if ($match_operator == 'CONTAINS') {
$query
->condition((new Condition('OR'))
->condition('rn.realname', '%' . $connection
->escapeLike($string) . '%', 'LIKE')
->condition('u.name', '%' . $connection
->escapeLike($string) . '%', 'LIKE'));
}
else {
$query
->condition((new Condition('OR'))
->condition('rn.realname', $connection
->escapeLike($string) . '%', 'LIKE')
->condition('u.name', $connection
->escapeLike($string) . '%', 'LIKE'));
}
if ($include_anonymous == FALSE) {
$query
->condition('u.uid', 0, '>');
}
$query
->range(0, 10);
$uids = $query
->execute()
->fetchCol();
$accounts = User::loadMultiple($uids);
/** @var \Drupal\user\Entity\User $account */
foreach ($accounts as $account) {
$matches[] = [
'value' => $this
->t('@realname (@id)', [
'@realname' => $account
->getDisplayName(),
'@id' => $account
->id(),
]),
'label' => $this
->t('@realname (@username)', [
'@realname' => $account
->getDisplayName(),
'@username' => $account
->getAccountName(),
]),
];
}
}
return $matches;
}