Adding an auto-complete field to a custom module form I am trying to add two auto-complete fields to a form I am using to generate two types of reports. What I have going on is that we have interfaced the CometChat chat system with Drupal using a custom module and now the customer wants reports for it. We realized that the best way for the user to narrow the result set is to let them use an auto-complete field for chatrooms by name and instant messages by individual.

Since I will be querying non-Drupal tables in the DB to do so I cannot just use a CCK field and the autocomplete widgets module (unless you know a trick on how to do that). I have never done an auto-complete field before in my life.

I know that I need to create the menu hook page callback, but I am not entirely sure how the JS and pingback should work to best do something like this. Does anyone know how to get started?

I am going over the code for the autocomplete widgets module to learn from it right now. But I would love any help with this.

Thanks!
There's a full example for Drupal 6 here: Textfield that uses autocomplete. The code will probably be useful to people on this site as well so I'll post i here:

The following is based on a module with the name: 'cities'

In your form function:

$form['city'] = array(
  '#type' =&gt; 'textfield',
  '#title' =&gt; 'City',
  '#maxlength' =&gt; 128,
  '#autocomplete_path' =&gt; 'cities/autocomplete',
);


In your module file:

function cities_menu(){
  // path with autocomplete function for cities
  $items['cities/autocomplete'] = array(
    'title' =&gt; 'Autocomplete for cities',
    'page callback' =&gt; '_cities_autocomplete',
    'access arguments' =&gt; array('use autocomplete'),  //or whatever permission makes sense
    'type' =&gt; MENU_CALLBACK
  );
  return $items;
}


Also in your module file:

function _cities_autocomplete($string) {
  $matches = array();
  //search table `cities` for cities that begin with the letters the user enters in the form
  $result = db_query_range("SELECT city FROM {cities} WHERE LOWER(city) LIKE LOWER('%s%')", $string, 0, 10);
  // add matches to $matches
  while ($data = db_fetch_object($result)) {
    $matches[$data-&gt;city] = check_plain($data-&gt;city);
  }
  // return for JS
  print drupal_to_js($matches);
  exit();
}