Entity view (Content)

How to implement Drupal AJAX Autocomplete

By sobayashi
Mar. 2, 2009

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.

In Drupal web development, AJAX functionality is provided through functions in the Javasript file drupal.js, and some AJAX functions are supported by Drupal core.

I am going to explain the autocomplete which is one of the AJAX functions implemented in Drupal. When users type into a text filed, new data from the server is dynamically loaded and displayed as a list of matching options. Exchanging data beteween client and server, and updating the content are handled by the autocomplete.js. The textfield type form input has the #autocomplete_path attribute which is the path that the AJAX autocomplete script uses as the source for autocompletion. You can easily implement the AJAX autocomplete to your form using the #autocomplete_path attribute.

Implementing the autocomplete contains two parts:1) a form input textfield and 2) a handler function to parse the request and return a response. There are build-in autocomplete handler functions such as user_autocomplete() and taxonomy_autocomplete().

Here is a simple example of how to implement the autocomplete uisng 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.

Also note that you need to use your autocomplete handler callback has proper access permission.It might be exposing some sensitive information on the site.

Building Rich Internet Apps with Drupal & HTML5
Learn the power of combining Drupal + HTML5 + CSS3 + JS
Post Tags: