Thursday, May 17, 2012

Tagged under: , , , , ,

How to use auto-complete textfield in Drupal

This is mostly applied to both Drupal 6 and 7, the only difference is Drupal 6 uses drupal_json() and Drupal 7 uses drupal_json_output(). Here's what I did.

Create a link to my form and a link to page that used for return autocomplete results:
//hook_menu
function my_module_menu() {

 $items['my_autocomplete_form'] = array(
'type' => MENU_CALLBACK,
'title' => 'My Autocomplete Form',
'access callback' => TRUE,
'page callback' => 'drupal_get_form',
'page arguments' => array('my_autocomplete_form')
);


$items['autocomplete'] = array(
'type' => MENU_CALLBACK,
'title' => 'Autocomplete',
'access callback' => TRUE,
'page callback' => 'my_autocomplete_form_result'
);

return $items;

}


Create content of my form:
function  my_autocomplete_form () {
$form = array();
 
$form['my_autocomplete_textfield'] = array(
'#title' => 'Text',
'#type' => 'textfield',
'#description' => 'This is a autocomplete textfield',
'#autocomplete_path' => 'autocomplete',
'#maxlength' => 500,
);

return $form;
}


Query whatever you want from database using the text you type in the textbox:
function istar_front_product_manager_result($string) {
$matches = array();

$result = db_query_range("SELECT nid, title FROM {node} WHERE LOWER(title) LIKE LOWER('%%" . $string . "%%')", 0, 10);
while ($row = $result->fetchObject()) {
$matches[$row->nid] = check_plain($row->title);
}

return drupal_json_output($matches);
}




0 comments:

Post a Comment