Thursday, 17 February 2011

Creating Autocomplete Text Fields

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['todo/autocomplete'] = 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);
drupal_json($matches);  

// we don't need goto next PHP
 
exit();
}
?>

5 comments:

  1. hi am a newbie in drupal have a doubt where this path 'path' => 'cities/autocomplete',
    and also need to know is this code is ok for custom field?

    ReplyDelete
  2. Hi,
    Yes this is ok..
    'path' => 'cities/autocomplete' this is actually return path of autocomplete result.

    function _cities_autocomplete($string) {....}

    this is the function for cities/autocomplete path.

    If any more problem plz let me know.


    Thanks

    ReplyDelete
  3. This code is working when we create a custom module..i have another doubt..we have write a textbox in page.tpl.php (in the theam page written as input type=text name=text_ucart) let me please know how can implement autosuggest on this?

    ReplyDelete
  4. thank you for your reply too :)

    ReplyDelete

Source base installation of php, mysql and apache in ubuntu/ linux

Compile and Install a LAMP(Linux/Apache/MySQL/PHP) Server from Source In the last post, I described the method to install a LAMP ser...