Autocomplete textfield in Drupal.

Share on FacebookTweet about this on TwitterShare on LinkedInShare on TumblrPin on PinterestDigg thisShare on StumbleUponEmail this to someone

Dear Friends, Last week I got a chance to work on drupal and had to add autocomplete functionality to textfields. I had to fetch/search data from database and show in text field.

Example: Suppose I want to make autocomplete text field for ‘author’ table:

CREATE TABLE `author` (
  `first_name` varchar(100) NOT NULL,
  `last_name` varchar(100) DEFAULT NULL,

Steps to achieve this are:

1. Create a menu hook in your .module file as below:

$items['search/get_author'] = array(
   'title'  => 'text matching',
   'page callback'  => 'author_autocomplete',
   'access arguments' => array('view keyword autocomplete'),
   'type'  => MENU_CALLBACK,

Here we are using existing search functionality.

2. Create function that we call for search from database as below:

function author_autocomplete($string='') {
  $matches = array();
   if($string) {
     $result = db_query_range("SELECT * FROM {author} WHERE first_name LIKE '%s%%' OR last_name LIKE '%s%%'", array($string, $string), 0,     variable_get('keyword_autocomplete_matches', 10));
       while ($data = db_fetch_object($result)) {
         $matches[$data->first_name . ' '. $data->last_name] = check_plain($data->first_name) . ' ' .check_plain($data->last_name);

3. Now create a textfiled with ‘autocomplete_path’ parameter using Drupal form API as below:

$form['Author'] = array(
  '#type' => 'textfield',
  '#title' => t('Author'),
  '#default_value' => $object['Author'],
  '#size' => 60,
  '#maxlength' => 64,
  '#autocomplete_path' => 'search/get_author',

Now, Let me explain the concept how it works.

When you type something to Author textfield autocomplete_path callback the ‘search/get_author’ -> Drupal menu hook look for page callback function ‘author_autocomplete’  -> Now function author_autocomplete generate the drupal_json data to autocmplete.js which is automatically included when you work under ‘search’ module.

Hope this will help new drupal developers and some experienced who did not work on this functionality.

Thanks and Regards,

Mahesh Salaria

Leave a Reply