Thursday, June 27, 2013

Auto Complete for Search and Other text fields

$form['example'] = array(
  '#type' => 'textfield',
  '#title' => t('Example Textfield'),
  '#autocomplete_path' => 'products/autocomplete',
);
 
/**
 * 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;
 
 
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'];
  }
print drupal_get_js($matches); exit;
or
  drupal_json($matches);  
}
 
 
Drupal will visualize all above-mentioned the following way: