drupal 7 custom search autocomplete using form field

1517

How to create Custom Search Autocomplete using Form Field.

drupal 7 custom search autocomplete using form field

Step1: Create Hook_menu


/**
* Implements hook_menu.
*/
function module_name_menu() {

$items['auto-search-form'] = array(
'title' => '',
'page callback' => 'drupal_get_form',
'page arguments' => array('auto_search_form'),
'access arguments' => array('access content'),
'type' => MENU_CALLBACK,
);

$items['college/autocomplete'] = array(
'title' => '',
'page callback' => '_college_autocomplete',
'access arguments' => array('access content'),
'type' => MENU_CALLBACK,
);

return $items;
}

Step2: Form,


/**
* Create Form.
*/

function auto_search_form($form, &$form_state){
$form['college'] = array(
'#type' => 'textfield',
'#title' => 'College',
'#maxlength' => 128,
'#autocomplete_path' => 'college/autocomplete',
);
return $form;
}

Step3:


/**
* Autocomplete callback function.
*/

function _college_autocomplete($string) {
$matches = array();
$result = db_select('node', 'n')
->fields('n', array('nid', 'title'))
->condition('n.title', '%' . db_like($string) . '%', 'LIKE')
->condition('n.type', 'college', '=') // content type college
->range(0, 15)
->execute();
foreach ($result as $row) {
$matches[check_plain($row->nid)] = check_plain($row->title);
}
drupal_json_output($matches);
}

OUTPUT:

drupal 7 custom search autocomplete using form field
drupal 7 custom search autocomplete using form field

LEAVE A REPLY

Please enter your comment!
Please enter your name here