function views_ajax_autocomplete_user

Page callback for views user autocomplete.

Parameters

string $string: (optional) A comma-separated list of user names entered in the autocomplete form element. If not passed, it is taken from the 'q' query string parameter.

Return value

Symfony\Component\HttpFoundation\JsonResponse

Related topics

1 call to views_ajax_autocomplete_user()
HandlerFilterUserNameTest::testUserAutocomplete in drupal/core/modules/views/lib/Drupal/views/Tests/User/HandlerFilterUserNameTest.php
Tests the autocomplete function.
1 string reference to 'views_ajax_autocomplete_user'
views_menu in drupal/core/modules/views/views.module
Implement hook_menu().

File

drupal/core/modules/views/includes/ajax.inc, line 291
Handles the server side AJAX interactions of Views.

Code

function views_ajax_autocomplete_user($string = NULL) {
  if (!isset($string)) {
    $string = drupal_container()
      ->get('request')->query
      ->get('q');
  }

  // The user enters a comma-separated list of user name. We only autocomplete the last name.
  $array = drupal_explode_tags($string);

  // Fetch last name
  $last_string = trim(array_pop($array));
  $matches = array();
  if ($last_string != '') {
    $prefix = count($array) ? implode(', ', $array) . ', ' : '';
    if (strpos('anonymous', strtolower($last_string)) !== FALSE) {
      $matches[$prefix . 'Anonymous'] = 'Anonymous';
    }
    $result = db_select('users', 'u')
      ->fields('u', array(
      'uid',
      'name',
    ))
      ->condition('u.name', db_like($last_string) . '%', 'LIKE')
      ->range(0, 10)
      ->execute()
      ->fetchAllKeyed();
    foreach ($result as $account) {
      $n = $account;

      // Commas and quotes in terms are special cases, so encode 'em.
      if (strpos($account, ',') !== FALSE || strpos($account, '"') !== FALSE) {
        $n = '"' . str_replace('"', '""', $account) . '"';
      }
      $matches[$prefix . $n] = check_plain($account);
    }
  }
  return new JsonResponse($matches);
}