Creating Autocomplete Text Fields similar to Autocomplete search fields !

pratyk - January 10, 2008 - 14:53

I am trying to create a module to register for an online course. It involves the students to input their name, address, email address and name of the school. Currently they are just text fields using the forms api. The problem is that a lot many a times, students from the same school enter the name of school in different manner and as such, one school is stored in the database under multiple names. This becomes an issue if i try to search for a school as not all the entries would come up.

I was thinking if it was possible to have an autocomplete text box similar to the autocomplete used in live search in drupal and the search box in browsers (top right) ..

has this been done by anyone ? can anyone help me out with this ??

thanks a lot. your help is well appreciated.

It's simple with form API.

havran - January 10, 2008 - 15:12

It's simple with form API. You must have set autocomplete path with autocomplete function callback in your hook_menu() .

<?php
  
   
// path with autocomplete function for cities
   
$items[] = array(
     
'path' => 'cities/autocomplete',
     
'title' => 'Autocomplete for cities',
     
'callback' => '_cities_autocomplete',
     
'access' => TRUE,
     
'type' => MENU_CALLBACK
   
);
?>

And in your form:

<?php
  $form
['city'] = array(
   
'#type' => 'textfield',
   
'#title' => 'City',
   
'#maxlength' => 128,
   
'#autocomplete_path' => 'cities/autocomplete',
  );
?>

And autocomplete function which search city in table cities looks like:

<?php
/**
* autocomplete helper
* $string = string for search
*/
function _cities_autocomplete($string) {
 
$matches = array();
 
// searching in database, only city column
 
$result = db_query_range("SELECT city FROM {cities} WHERE LOWER(city) LIKE LOWER('%s%%')", $string, 0, 10);
 
// found wrote into $matches
 
while ($data = db_fetch_object($result)) {
   
$matches[$data->city] = check_plain($data->city);
  }
 
// return for JS
 
print drupal_to_js($matches);
 
// we don't need goto next PHP
 
exit();
}
?>

Something looks like this working for me (Drupal 5 offcourse). Here is full article but only in Slovak language (sorry) :). http://www.fem.uniag.sk/havran/blog/ako-v-drupale-na-funkciu-autocomplet...

--
My blog - Havran's mini-blog
My first drupal site - http://www.enigma.sk/

yes, it is so simple

ardnet - June 16, 2008 - 08:03

Yes, it does so simple.

thank you so much.

 
 

Drupal is a registered trademark of Dries Buytaert.