4

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' => 'textfield',
  '#title' => t('Keywords'),
  '#size' => '40',
  '#multiple' => TRUE,
  '#autocomplete_path' => 'papers_pub_search/keywords_autocomplete'
);

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

1 Answer 1

13

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')->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);
    }
  }

  drupal_json_output($matches);
}

This is the result.

one username

two usernames

three usernames

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

  drupal_json_output($matches);
}

usernames are not repeated

4

Your Answer

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

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