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();
}?>
hi am a newbie in drupal have a doubt where this path 'path' => 'cities/autocomplete',
ReplyDeleteand also need to know is this code is ok for custom field?
Hi,
ReplyDeleteYes 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
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?
ReplyDeletethank you for your reply too :)
ReplyDeleteno answer :(
ReplyDelete