By default, the Drupal 7 core provides the necessary functionality to implement the autocomplete widget for users and taxonomy (Hint: search the Drupal 7 core for '#autocomplete_path'). With that in mind, outside of a quick hook_form_alter all I needed to do was appropriate the existing code and then tweak it to my needs.
You can add own autocomplete path to any form fields:
Use hook_form_alter to set an autocomplete path for the field
/**
* Implements hook_form_alter
* Implements hook_form_alter
* Alter form ids are views_exposed_form adding custome ajax path in search location filter;
*/
function hook_form_alter(&$form, &$form_state, $form_id){
if($form['#form_id']=='views_exposed_form' && $form['#id']=='views-exposed-form-search-store-page')
{
// field name for auto complete
$form['field_location_locality']['#autocomplete_path']='demo-autocomplete-engine';
}
}
Define a menu callback for the autocomplete path in hook_menu
/**
* Implementation of hook_menu.
*/
function hook_menu() {
$items = array();
$items['demo-autocomplete-engine'] = array(
'page callback' => 'hook_autocomplete',
'access callback' => TRUE,
);
return $items;
}
* Implementation of hook_menu.
*/
function hook_menu() {
$items = array();
$items['demo-autocomplete-engine'] = array(
'page callback' => 'hook_autocomplete',
'access callback' => TRUE,
);
return $items;
}
Have the callback query the database
/**
* Implements custome autocomplete function
* Retrieve a JSON object containing autocomplete suggestions for field value.
*/
function hook_autocomplete($text) {
global $base_url,$base_path,$theme_path,$user;
$results = array();
$query = db_select('field_data_field_location', 'c');
$query
->condition('c.field_location_locality', '%' . db_like($text) . '%', 'LIKE')
->fields('c', array('field_location_locality'))
->groupBy('field_location_locality')
->orderBy('field_location_locality', 'ASC')
->range(0,10);
$sql_results = $query->execute();
if(!empty($sql_results) AND $sql_results->rowCount() > 0){
foreach ($sql_results as $row) {
$results[$row->field_location_locality] = check_plain($row->field_location_locality);
}
}else{
$results[0] = check_plain('No results. Please try something else');
}
drupal_json_output($results);
}
After this step assure that your cache are clear.
The final function in our module queries our database and returns 10 results. The autocomplete widget uses JavaScript, so after the $results array has been populated we then convert the output to json!
No comments:
Post a Comment