Drupal 6: Form Auto Complete field with example

The Autocomplete field will suggest the information while user typing initial values. Inform text field fields we can able to change as autocomplete field instead of the normal text field. The below is the example text file into a autocomplete field in Drupal 6.

Sample Code:

/**
 * Implementation of hook_menu().
 */
function edu_studytime_menu() {
  $items['node/list/form'] = array(
    'title' => 'Node List form',
    'page callback' => 'drupal_get_form',
    'page argument' => 'codeexpertz_node_list_form',
    'access arguments' => TRUE,
    'type' => MENU_CALLBACK,
  );
  $items['edu_studytime/book/autocomplete'] = array(
    'title' => 'Autocomplete for Title',
    'page callback' => 'codeexpertz_node_autocomplete',
    'access arguments' => TRUE.
    'type' => MENU_CALLBACK
  );
}
 
/**
 * Custom Form.
 */
function codeexpertz_node_list_form($form, $form_state) {
  $form['book'] = array(
    '#type' => 'textfield',
    '#title' => 'Book',
    '#required' => TRUE,
    '#maxlength' => 128,
    '#autocomplete_path' => 'edu_studytime/book/autocomplete',
    '#default_value' => $bookTitle,
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Update',
  );
  return $form;
}
 
/**
 * Autocomplete node title for Form.
 */
function codeexpertz_node_autocomplete($string) {
  $matches = array();
  $result = db_query_range("SELECT title FROM {node} WHERE status = 1 AND LOWER(title) LIKE LOWER('%s%')", trim($string), 0, 10);
  // add matches to $matches
  while ($data = db_fetch_object($result)) {
    $matches[$data->title] = check_plain($data->title);
  }
  print drupal_to_js($matches);
  exit();
}
Category: