Drupal: Autocomplete for any CCK text field or any form field

Published on April 30, 2012

At present no module is available for CCK autocomplete field but you can achieve this by custom code : Edit 03-March-2012: Check out http://drupal.org/project/autocomplete_widgets

Step 1 : Use hook_form_alter(&$form, &$form_state, $form_id) and create a case for your $form_id. Step 2 : Add '#autocomplete_path' to the field where you want to add autocomplete functionality. Take reference of code given below:

<?php
$form['my_autocomplete_field'] = array(
  '#title' => t("Autocomplete Textfield"),
  '#type' => 'textfield',
  '#autocomplete_path' => 'autocomplete/example/textfield',
);
?>

Step 3 : And in hook_menu():

<?php
$items['autocomplete/example/textfield'] = array(
  'page callback' => 'autocomplete_example_textfield',
  'access callback' => TRUE,
  'weight' => 1,
  'type' => MENU_CALLBACK,
);
?>

Step 4 : Now define the callback function:

<?php
function autocomplete_example_textfield($string) {
  $items = array();
  $query = db_select('node', 'n');
  $value = $query->fields('n', array('nid', 'title'));
  $value = $query->condition(db_and()->condition('n.status', 1)->condition('title', '%' . db_like($string) . '%', 'LIKE'))
    ->range(0, 10) // Limit results for performance
    ->execute();

  foreach ($value as $val) {
    $items[$val->title] = check_plain($val->title); // Use title as key and value for autocomplete
  }
  print drupal_json_output($items);
  exit();
}
?>

Source: http://drupal.org/node/1117562