I have the following code to add a field to my custom module to add in users. But I can only add in one user using the user/autocomplete feature.

$form['usershare'] = array(   
  '#title' => t('Share Collection with:'),
  '#type' => 'textfield',   
  '#autocomplete_path' => 'user/autocomplete'  

How do I enable multiple users? These users should be separated by a comma on the back end for me to process it.


as @Geat said:

Your form should be like below.

    $form['usershare'] = array(   
      '#title' => t('Share Collection with:'),
      '#type' => 'textfield',   
      '#autocomplete_path' => 'user/autocomplete',
      '#multiple' => TRUE,

    // Implemenbts hook_menu() for user/autocomplete path.
    function module_name_menu() {  
      $items['user/autocomplete'] = array(
        'page callback' => '_user_autocomplete',
        'access arguments' => array('access user autocomplete'),
        'type' => MENU_CALLBACK
      return $items;

    // Implements callback function to get users in autocomplete with comma seperated
    function _user_autocomplete($string) {
      if ($string) {
        $items = array_map('trim', explode(',', $string));
        $last_item = array_pop($items);
        $prefix = implode(', ', $items);
        $result = db_select('users')->fields('users', array('name'))->condition('name', '%' . db_like($last_item) . '%', 'LIKE')->range(0, 10)->execute();
        foreach ($result as $user) {
          $value = !empty($prefix) ? $prefix . ', ' . $user->name : $user->name;
          $matches[$value] = check_plain($value);
    // return output in JSON format.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.