You are here

function library_patron_autocomplete in Library 7

Same name and namespace in other branches
  1. 6.2 library.module \library_patron_autocomplete()

Returns a pipe-delimited string of autocomplete results for existing users.

Parameters

string $string: The search string of the user.

1 string reference to 'library_patron_autocomplete'
library_menu in ./library.module
Implements hook_menu().

File

./library.module, line 1557

Code

function library_patron_autocomplete($string) {
  $matches = array();
  $check_profile_fields = false;
  if (module_exists('profile')) {
    $profile_fields = array();
    $fields = db_select('profile_field', 'pf')
      ->fields('pf', array(
      'fid',
      'name',
    ))
      ->condition('type', 'textfield')
      ->execute();
    foreach ($fields as $field) {
      if (variable_get('library_profile_' . $field->name, 0) == 1) {
        $profile_fields[$field->name] = $field->fid;
      }
    }
    if (!empty($profile_fields)) {
      $check_profile_fields = true;
    }
  }
  if ($check_profile_fields) {
    $entries = db_select('profile_value', 'pv')
      ->fields('pv', array(
      'uid',
    ))
      ->condition('fid', $profile_fields, 'IN')
      ->condition('value', '%' . db_like(check_plain($string)) . '%', 'LIKE')
      ->groupBy('pv.uid')
      ->range(0, 10)
      ->execute();
    foreach ($entries as $entry) {
      $user = user_load($entry->uid);
      $name = null;
      foreach ($profile_fields as $field_name => $fid) {
        if ($name) {
          $name .= ', ';
        }
        $name .= $user->{$field_name};
      }
      $name .= ' (' . $user->name . ')';
      $matches[$name . ' [uid:' . $user->uid . ']'] = check_plain($name);
    }
  }
  else {
    $select = db_select('users', 'u')
      ->fields('u', array(
      'uid',
      'name',
    ))
      ->condition('status', 1)
      ->condition('name', '%' . db_like(check_plain($string . '')) . '%', 'LIKE')
      ->orderBy('name')
      ->range(0, 10);
    $result = $select
      ->execute()
      ->fetchAllAssoc('uid');
    foreach ($result as $patron) {
      if (isset($patron->name) && isset($patron->uid)) {
        $matches[$patron->name . ' [uid:' . $patron->uid . ']'] = check_plain($patron->name);
      }
    }
  }
  print drupal_json_encode($matches);
  exit;
}