Creating module with autocomplete and accepting multiple values in textfield I am creating my own form in my module using the Form API. 

How do I enter multiple values in the below textfield and have it autocompleted, and suggested (separated by commas, for example)?

Right now it takes whatever is in the textfield box as one single big string.

$form['keywords'] = array(
  '#type' =&gt; 'textfield',
  '#title' =&gt; t('Keywords'),
  '#size' =&gt; '40',
  '#multiple' =&gt; TRUE,
  '#autocomplete_path' =&gt; 'papers_pub_search/keywords_autocomplete'
);

function _autosearch($string) {
  $query = "SELECT name FROM users WHERE name LIKE :name";
  $result = db_query($query, array(':name'=&gt; '%' . db_like($string) . '%'));
  foreach($result as $row) {
    $match[$row-&gt;name] = check_plain($row-&gt;name);
  }
  drupal_json_output($match);
}
You can use the following code.

function _autosearch($string) {
  $matches = array();

  if ($string) {
    $items = array_map('trim', explode(',', $string));
    $last_item = array_pop($items);
    $prefix = implode(', ', $items);

    $result = db_select('users')-&gt;fields('users', array('name'))-&gt;condition('name', '%' . db_like($last_item) . '%', 'LIKE')-&gt;range(0, 10)-&gt;execute();
    foreach ($result as $user) {
      $value = !empty($prefix) ? $prefix . ', ' . $user-&gt;name : $user-&gt;name;
      $matches[$value] = check_plain($value);
    }
  }

  drupal_json_output($matches);
}


This is the result.







If you want to avoid a username can be used more than once, then you can use the following code.

function _autosearch($string = '') {
  $matches = array();

  if ($string) {
    $items = array_map('trim', explode(',', $string));
    $last_item = array_pop($items);
    $prefix = implode(', ', $items);

    $result = db_select('users')-&gt;fields('users', array('name'))-&gt;condition('name', '%' . db_like($last_item) . '%', 'LIKE')-&gt;range(0, 10)-&gt;execute();
    foreach ($result as $user) {
      if (!in_array($user-&gt;name, $items)) {
        $value = !empty($prefix) ? $prefix . ', ' . $user-&gt;name : $user-&gt;name;
        $matches[$value] = check_plain($value);
      }
    }
  }

  drupal_json_output($matches);
}