0

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.

1

1 Answer 1

1

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.
    drupal_json_output($matches);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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