How to implement a AJAX autocomplete with Drupal (in 5 minutes)
Sure there are modules for getting an auto complete textfield in Drupal. But where would the fun be then :)
Here I will show you how to write your own auto complete AJAX textfield. It is surprisingly easy and we will walk through all the steps from defining a text box to writing a SQL query to fetch the results to display.
Basically there are following steps to the whole process:
1. Define a textfield which will act as an auto complete
2. Define a menu item which will be invoked by our textfield(form element)
3. Call a function (handler function) which will hit a SQL query and fetch the results.
1. Define the form element - textfield:
$form['item'] = array(
'#type' => 'textfield',
'#title' => t('Select the entry'),
'#autocomplete_path' => 'nodes/autocomplete',
);
Drupal offers an #autocomplete_path attribute for textfields. This tells Drupal to look at the menu which handles the url and react accordingly. So next we define the menu which will handle this URL
2. Menu item to handle the URL
$items['nodes/autocomplete'] = array(
'page callback' => 'nodes_autocomplete',
'access arguments' => user_access('access example autocomplete'),
'type' => MENU_CALLBACK,
);
This entry in the hook_menu() will forward the request to the function
nodes_autocomplete()
3. Guts of the autocomplete
In the function, nodes_autocomplete() you will implement the code the return the list of items to be shown in the textfield. In this case, we can fetch a node of type my_type
function nodes_autocomplete($string){
$items = array();
$result = db_query("SELECT nid, title FROM {node} WHERE status = 1 AND
type='my_type' AND title LIKE LOWER ('%s%%')", $string) ;
while($obj = db_fetch_object($result)) {
$items[$obj->nid] = check_plain($obj->title);
}
drupal_json($items);
}
This function makes the SQL query to retrive all nodes of type my_type and searches the title for autocomplete. drupal_json() formats the data in JSON format. So the $items will be returned as JSON which our javascript will be able to handle and show the results.
This is all you need and you should be on your way to having your own autocomplete textfield in Drupal. Drupal has all the built in support for these kinds of calls.