4.7.x taxonomy.module taxonomy_autocomplete($vid, $string = '')
5.x taxonomy.module taxonomy_autocomplete($vid, $string = '')
6.x taxonomy.pages.inc taxonomy_autocomplete($vid, $string = '')
7.x taxonomy.pages.inc taxonomy_autocomplete($field_name = '', $tags_typed = '')

Helper function for autocompletion

1 string reference to 'taxonomy_autocomplete'
taxonomy_menu in modules/taxonomy/taxonomy.module
Implementation of hook_menu().

File

modules/taxonomy/taxonomy.pages.inc, line 113
Page callbacks for the taxonomy module.

Code

function taxonomy_autocomplete($vid, $string = '') {
  // The user enters a comma-separated list of tags. We only autocomplete the last tag.
  $array = drupal_explode_tags($string);

  // Fetch last tag
  $last_string = trim(array_pop($array));
  $matches = array();
  if ($last_string != '') {
    $result = db_query_range(db_rewrite_sql("SELECT t.tid, t.name FROM {term_data} t WHERE t.vid = %d AND LOWER(t.name) LIKE LOWER('%%%s%%')", 't', 'tid'), $vid, $last_string, 0, 10);

    $prefix = count($array) ? implode(', ', $array) . ', ' : '';

    while ($tag = db_fetch_object($result)) {
      $n = $tag->name;
      // Commas and quotes in terms are special cases, so encode 'em.
      if (strpos($tag->name, ',') !== FALSE || strpos($tag->name, '"') !== FALSE) {
        $n = '"' . str_replace('"', '""', $tag->name) . '"';
      }
      $matches[$prefix . $n] = check_plain($tag->name);
    }
  }

  drupal_json($matches);
}

Comments

karlis’s picture

One of our editors was not happy about the behaviour of this autocomplete, it was still showing the list of suggestions after a term had been "closed for suggestion", that is, a comma had been entered after the term. I think adding one extra line and an if condition like this fixes the problem:

function taxonomy_autocomplete($vid, $string = '') {
  // The user enters a comma-separated list of tags. We only autocomplete t
  $array = drupal_explode_tags($string);
  $close_complete = substr(trim($string),-1); //what is the last character?

  // Fetch last tag
  $last_string = trim(array_pop($array));
  $matches = array();
  if ($last_string != '' && $close_complete != ',') { //don't show the list if the last character is a ','
. . .