Ajax Autocomplete Textfield

Public

Get raw version
php
  1. function module_name_form() {
  2. $form = array();
  3.  
  4. $form['city'] = array(
  5. '#title' => t('City'),
  6. '#type' => 'textfield',
  7. '#autocomplete_path' => 'example/autocomplete',
  8. );
  9.  
  10. $form['submit'] = array(
  11. '#type' => 'submit',
  12. '#value' => 'Save',
  13. );
  14.  
  15. return $form;
  16. }
Get raw version
php
  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. }
Get raw version
php
  1. function _module_name_autocomplete($string) {
  2. $matches = array();
  3.  
  4. // Some fantasy DB table which holds cities
  5. $query = db_select('cities', 'c');
  6.  
  7. // Select rows that match the string
  8. $return = $query
  9. ->fields('c', array('city'))
  10. ->condition('c.city', '%' . db_like($string) . '%', 'LIKE')
  11. ->range(0, 10)
  12. ->execute();
  13.  
  14. // add matches to $matches
  15. foreach ($return as $row) {
  16. $matches[$row->city] = check_plain($row->city);
  17. }
  18.  
  19. // return for JS
  20. drupal_json_output($matches);
  21. }