Ajax / Autocomplete field howto

Autocomplete fields are the bomb. They pop up selectable suggestions while a user types text in a field, increasing usability at relatively low cost.

Here's how to write a simple module that provides a form with an autocomplete text field that suggests existing usernames to the user.

This module is for demonstration only, and should definately not be run on a live site, as it will expose all your registered usernames!

1. The form creation method:

<?php
function aademo_form(){
  return array(
   
'user' => array(
     
'#title' => 'User name',
     
'#type' => 'textfield',
     
'#autocomplete_path' => 'ajax/user/',
    ),
  );
}
?>

You'll notice the #autocomplete_path attribute in addition to a simple text field definition. This tells Drupal that this is an autocomplete field, as well as where to fetch suggestions from. We'll tell drupal what to do with that path in a moment.

2. Registering a path to the form, and a path for to the autocomplete:

<?php
function aademo_menu(){
  return array(
   
'ajax/user' => array(
     
'page callback' => 'aademo_getusers',
     
'access arguments' => array(TRUE),
     
'type' => MENU_CALLBACK,
    ),
   
'demo/form' => array(
     
'title' => 'Demo form',
     
'page callback' => 'drupal_get_form',
     
'page arguments' => array('aademo_form'),
     
'access arguments' => array(TRUE),
     
'type' => MENU_CALLBACK,
    ),
  );
}
?>

The hook_menu hook in Drupal 6 is used to register paths within a site, and link those pathes to functionality. Here we've specified that typing in www.mysite.com/demo/form will call the drupal_get_form method, and pass 'aademo_form' to it. In essence displaying our form.

Typing in www.mysite.com/ajax/user will cause Drupal to call the 'aademo_getusers' method, and display a list of registered usernames on the site (in a format that javascript can understand - JSON).
Whatever is added to the back of any registered path (eg. "sss" in www.mysite.com/ajax/user/sss) will be passed on to the function that is linked to the registered path.

3. A method to generate suggestions:

<?php
function aademo_getusers($part){
 
$result = db_query('select name from users where name like "%s%%";', $part);
 
$users = array();
  while (
$row = db_fetch_array($result)){
   
$users[] = $row['name'];
  }
 
  print
drupal_to_js(
   
$users
 
); 
}
?>

The $part variable that is passed to this method is going to contain whatever the user has typed in the field so far. This method in particular looks in the user table for anything that starts with whatever is in the $part parameter. The javascript on the client side that manages the autocomplete field is expecting data in JSON, which is what the drupal_to_js method does.

And that's it!

You can download a complete copy of this demo module below:

AttachmentSize
aademo.zip915 bytes