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;
}
?>










Great work.... again.
As always, your post is extremely clear and helpful. Helped me out of a bind once again. Kudos sir.
Pretty useful tutorial,
Pretty useful tutorial, although i would suggest to use drupal_json instead of drupal_to_js. It solves a few things:
1) no need to exit() afterwards
2) Devel module doesn't add its DIVs to the output
3) the content-type header is automatically set (text/javascript instead of application/json, but it doesn't matter much)
Submitting when suggestion is clicked
Hello,
Thanks for this tutorial, was really helpful. I'm wondering how I can have the form submit when they select one of the auto complete suggestions?
Thanks