4

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!

7

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' => 'textfield',
  '#title' => 'City',
  '#maxlength' => 128,
  '#autocomplete_path' => 'cities/autocomplete',
);

In your module file:

function cities_menu(){
  // path with autocomplete function for cities
  $items['cities/autocomplete'] = array(
    'title' => 'Autocomplete for cities',
    'page callback' => '_cities_autocomplete',
    'access arguments' => array('use autocomplete'),  //or whatever permission makes sense
    'type' => 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->city] = check_plain($data->city);
  }
  // return for JS
  print drupal_to_js($matches);
  exit();
}
  • Thanks, I never found this page on my own. That helps a lot. – Patrick Apr 19 '12 at 19:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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