Drupal: Using #autocomplete_path on textfield elements

Sometimes it is useful to have some sort of auto-complete features when typing. Drupal provides some API for you to hook into in case you want to add it.

Firstly, when declaring your textfield in the form, add the #autocomplete_path attribute in your form declaration.

$form['example'] = array(
  '#type' => 'textfield',
  '#title' => t('Example Textfield'),
  '#autocomplete_path' => 'path/to/callback',
);

Now you need to create a menu callback which hooks the path to the callback in your hook_menu() definition.

$path['path/to/callback'] = array(
  'page callback' => 'module_auto_complete_does_something',
  'type' => MENU_CALLBACK,
);

Finally, you need to create the callback. It will need to return some JSON output, but all we need to worry about is creating an array which with meaningful keys. The values in the array are used for labels. drupal_json() will handle the rest.

function module_auto_complete_does_something($string) {
  $matches = array();
  $res = db_query("SELECT * FROM term_data WHERE name ~* '%s' ORDER BY LOWER(name)", $string);

  while ($row = db_fetch_array($res)) {
    $matches[$row['tid']] = $row['name'];
  }

  // Optional: Sort the results
  // asort($matches);

  drupal_json($matches);
}

And there you have it, a fully working auto complete for a textfield.

Additional arguments:

If you need to pass additional arguments to the callback, you can do so by modifying the menu hook.

$path['path/to/callback/%/%'] = array(
  'page callback' => 'module_auto_complete_does_something',
  'page arguments' => array(3, 4),
  'type' => MENU_CALLBACK,
);

The $string argument is automatically passed to the function by the API. If you wish to add arguments to the callback, place the $string argument as the last parameter.

function module_auto_complete_does_something($arg1, $arg2, $string) {
  ...

 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog