Adding a multiple user autocomplete field to Drupal

with terms

The drupal user_autocomplete function is very handy for form fields where you are entering a single username.  But what about cases where you want your users to be able to enter multiple usernames?  Turns out that this is very easy to do without having to write any JavaScript.
 
drupal autocomplete field, multiple usernames

 
These steps are for Drupal 5.x
 
Add this to your module's hook_menu:
 

$items[] = array(
  'path' => 'user/autocompletec',
  'title' => t('user autocomplete comma delimited'),
  'callback' => 'user_autocomplete_comma',
  'access' => TRUE,
  'type' => MENU_CALLBACK
);

 
Then, add this function to your module:
 

/**
 * Autocomplete for a comma delimted user list
 */
function user_autocomplete_comma($string) {
  $matches = array();
  $names = explode(",", $string);
  foreach($names as &$s) {
    $s=trim($s);
  }
  $name = array_pop($names);
  $result = db_query_range("SELECT name FROM {users} WHERE LOWER(name) LIKE LOWER('%s%%')", $name, 0, 10);
  while ($user = db_fetch_object($result)) {
    if (count($names) > 0) {
      $matches[implode(", ",$names) .", ". $user->name] = check_plain($user->name);
    }
    else {
      $matches[$user->name] = check_plain($user->name);
    }
  }
  print drupal_to_js($matches);
  exit();
}

 
The key here is being sure to prepend the already entered usernames to the $matches array key for the new username.  Otherwise all the existing usernames will get wiped out by the new one.
 
Lastly, add this to your form field:
 

'#autocomplete_path' => 'user/autocompletec',

 
Note that you may need to empty the cache_menu table in your drupal database before the new menu callback will work.