Skip to content

Instantly share code, notes, and snippets.

@kevinchampion
Created August 27, 2012 17:04
Show Gist options
  • Save kevinchampion/3490423 to your computer and use it in GitHub Desktop.
Save kevinchampion/3490423 to your computer and use it in GitHub Desktop.
Drupal username autocomplete callback
/**
* Ajax callback function for username autocomplete field.
*
* @param $name
* String, the portion of the autocomplete field already entered.
*/
function _cosign_impersonate_username_autocomplete($name = '') {
$matches = array();
if ($name) {
$query = db_select('users', 'u');
$return = $query
->fields('u', array('name'))
->condition('u.name', '%' . db_like($name) . '%', 'LIKE')
->range(0, 10)
->execute();
foreach ($return as $row) {
$matches[$row->name] = check_plain($row->name);
}
}
return drupal_json_output($matches); // Returns the data in JSON format
}
/**
* Helper to retrieve users and organize them by role to help the impersonater
* figure out which user to impersonate.
*
* @return
* HTML output of a table of users by role.
*/
function cosign_impersonate_retrieve_user_table() {
$output = '';
$query = db_select('users', 'u');
$query->join('users_roles', 'ur', 'u.uid = ur.uid');
$query->join('role', 'r', 'ur.rid = r.rid');
$return = $query
->fields('u', array('name'))
->fields('r', array('name'))
->orderBy('r.name', 'ASC')
->orderBy('u.name', 'ASC')
->execute();
$users_by_role = array();
foreach ($return as $row) {
$users_by_role[$row->r_name][] = $row->name;
}
foreach ($users_by_role as $role => $users) {
$output .= '<h4>' . $role . '</h4><ul><li>' . implode('</li><li>', $users) . '</li></ul>';
}
return $output;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment