Sometimes in the web development process the need arises to create autocomplete field in order to enhance usability. As worked examples of such fields widgets for cck-fields Node reference and User reference can be mentioned.
Let's look at some attempts of program creation of such fields. According to Drupal Forms API reference #autocomplete_path function can be added only for textfield element. This feature will identify the path through which Drupal JavaScript-code that is automatically turned on will send HTTP-requests, using JQuery.
First of all, we'll announce textfield in the form:
php $form['example'] = array( '#type' => 'textfield', '#title' => t('Example Textfield'), '#autocomplete_path' => 'products/autocomplete', );
Now we'll identify callback for autocomplete in hook_menu():
php /** * Implementation of hook_menu */ function module_menu() { $items['products/autocomplete'] = array( 'page callback' => 'module_products_autocomplete', 'type' => MENU_CALLBACK, 'access arguments' => array('administer nodes'), ); return $items; }
Finally, we must describe callback function itself that will transfer some array of drupal_json() function:
php function module_products_autocomplete($string) { $matches = array(); $res = db_query("SELECT title, nid FROM {node} WHERE LOWER(title) LIKE LOWER('%s%')", $string); while ($row = db_fetch_array($res)) { $matches[$row['nid']] = $row['title']; } drupal_json($matches); }
Now we have a full-blown autocomplete field.