Code Snippets

Guide to Drupal AJAX Autocomplete implementation

AJAX helps you create better, faster and more user-friendly web applications with its Javascript and HTTP base. It allows the page content to be updated without reloading a whole page. One of the great functions of AJAX is the autocomplete. Read more about AJAX autocomplete on this blog post!

Simple example of how to implement the autocomplete using the user_autocomplete() function:

function example_form(){  
  $form['item'] = array(   
    '#type' => 'textfield',   
    '#autocomplete_path' => 'user/autocomplete'  
    ); 
  }

 

This user/autocomplete path calls the user_autocomplete() function and loads matching user names. 

Also, you can create a custom autocomplete handler to meet a need for your site. Let’s say you have a text field which asks users to select a node item on the site.

function example_form(){  
  $form['item'] = array(   
    '#type' => 'textfield',   
    '#autocomplete_path' => 'example/autocomplete' 
    ); 
  }

function example_menu($may_cache) {  
  $item[] = array(   
    'path' => 'example/autocomplete',   
    'callback' => 'example_autocomplete',   
    'access' => user_access('access example autocomplete')  
    ); 
  }

function example_autocomplete($string){
  $items = array();  
  $result = db_query("SELECT nid, title FROM {node} WHERE status = 1 AND title LIKE ''%s%%', $string");
  
  while($obj = db_fetch_object($result)) {
    $items[$obj->nid] = check_plain($obj->title);
  }
  print drupal_to_js($items); 
  exit();
}

User input is passed from the parameter and the array of matching items is printed as the response. Note that you need to escape the node titles using check_plain() because the values are HTML. 

Resource Tags: