Drupal 6: Creating an autocomplete field using the forms api and a menu callback

In this snippet, I’ll explain how to implement an autocompleting field using the forms API and a menu callback. The first thing you’ll need to create is the callback function that queries the database and returns an non-themed javascript result. In this function I’ll return a list of node IDs and their titles:

<?php
function MYMODULE_autocomplete_node($userString) {
  // create the SQL to query the node table
  $sql = "select nid, title from {node} where status='1' and lower(title) like lower('%%%s%%') order by title asc";

  // query the database
  $resource = db_query_range($sql, $userString, 0, 10);

  // loop through the results and create an associative array
  $results = array();
  while ($row = db_fetch_array($resource)) $results[$row['nid']] = $row['title'];

  // output the results in javascript
  print drupal_to_js($results);

  // exit, to prevent your results form hitting the theme layer
  exit();
}
?>

Next create a menu item:

<?php
function MYMODULE_menu() {
  $items[] = array();
  // ...code...
  $items['MYMODULE/autocomplete/node'] = array(
    'type' => MENU_CALLBACK,
    'access arguments' => array('access content'),
    'page callback' => 'MYMODULE_autocomplete_node',
  );
  // ...code...
  return $items;
?>

Now if you flush your menu cache and go to your newly created menu path, you should see a list of nodeID and their titles formatted in JSON. Lastly, you’ll need to create the form element:

<?php
function MYMODULE_form() {
  $form = array();
  // ...code...
  $form['MYFIELDNAME'] = array(
    '#type' => 'textfield',
    '#title' => t('MYFIELDTITLE'),
    '#autocomplete_path' => 'MYMODULE/autocomplete/node',
  );
  // ...code...
  return $form;
}
?>

Updated: