How To Create an Ajax Autocomplete Textfield In Drupal 7

People are lazy by nature and love when something is done for them automatically. As web developers, we can always use this need in our website designs by creating different autocomplete fields to ease website visitor's experience. Being the best CMS platform outhere, Drupal allows us to create autocomplete fields within a blink of an eye. Here’s how to do this: Let’s imagine, you’re building some form where you want to help user with an autocomplete. For example, this can be a "City" input textfield. You can have something similar to the following form:

  1. function module_name_form() {
  2. $form = array();
  3. $form['city'] = array(
  4. '#title' => t('City'),
  5. '#type' => 'textfield',
  6. '#autocomplete_path' => 'example/autocomplete',
  7. );
  8. $form['submit'] = array(
  9. '#type' => 'submit',
  10. '#value' => 'Save',
  11. );
  12. return $form;
  13. }

The most interesting part here is: '#autocomplete_path' => 'example/autocomplete' which defines an autocomplete callback for our textfield. When user types something into our textfield, Drupal sends a request via this url to send data you input and to receive suggestions via json if there are any. To make Drupal aware of this path, let’s add it to the menu system:

  1. function module_name_menu() {
  2. $items['example/autocomplete'] = array(
  3. 'page callback' => '_module_name_autocomplete',
  4. 'access arguments' => array('access example autocomplete'),
  5. 'type' => MENU_CALLBACK
  6. );
  7. return $items;
  8. }

The last step is to create a _module_name_autocomplete function which will look for a suggestion and return it to the user.

  1. function _module_name_autocomplete($string) {
  2. $matches = array();
  3. // Some fantasy DB table which holds cities
  4. $query = db_select('cities', 'c');
  5. // Select rows that match the string
  6. $return = $query
  7. ->fields('c', array('city'))
  8. ->condition('c.city', '%' . db_like($string) . '%', 'LIKE')
  9. ->range(0, 10)
  10. ->execute();
  11. // add matches to $matches
  12. foreach ($return as $row) {
  13. $matches[$row->city] = check_plain($row->city);
  14. }
  15. // return for JS
  16. drupal_json_output($matches);
  17. }

In this function we query DB to find a match for a string typed in by a user. I use Dynamic queries (http://drupal.org/node/310075) to get data from a DB, if you feel yourself more comfortable with a SQL approach, feel free to use it as well. The current query is a fantasy one, yours can be a very different from this. If you want for a more advanced example, look in to the Drupal’s core taxonomy autocomplete function which can be found in ‘modules/taxonomy/taxonomy.pages.inc’, line 79: function taxonomy_autocomplete. All in all, I guess now you have an idea about hot to create an autocomplete text field in your custom Drupal 7 module.

Happy Drupal Coding!