Skip to content

Instantly share code, notes, and snippets.

@wxactly
Last active June 21, 2016 15:40
Show Gist options
  • Save wxactly/75cf2761379f17d9b0c4 to your computer and use it in GitHub Desktop.
Save wxactly/75cf2761379f17d9b0c4 to your computer and use it in GitHub Desktop.
Drupal Search API - Simple RedHen contact autocomplete
<?php
/**
* Implements hook_menu().
*/
function MY_MODULE_menu() {
$items['MY_MODULE/redhen/contact/autocomplete'] = array(
'title' => 'Autocomplete for RedHen Contacts',
'page callback' => 'MY_MODULE_contact_autocomplete',
'access callback' => 'redhen_contact_access',
'access arguments' => array('edit'),
'type' => MENU_CALLBACK,
);
return $items;
}
/**
* Contact autocomplete callback.
*
* @param string $search
* String for search.
*/
function MY_MODULE_contact_autocomplete($search) {
$index = search_api_index_load('redhen_contacts');
$query = new SearchApiQuery($index);
$query->keys($search);
$query->sort('search_api_relevance');
$query->range(NULL, 10);
$data = $query->execute();
$results = array();
if (!empty($data['results'])) {
$contacts = redhen_contact_load_multiple(array_keys($data['results']));
foreach ($contacts as $contact) {
$wrapper = $contact->wrapper();
$contact_identifier = $wrapper->full_name->value() . ' (' . $wrapper->getIdentifier() . ')';
$contact_name = $wrapper->full_name->value() . ' <' . $wrapper->email->value() . '>';
$results[$contact_identifier] = check_plain($contact_name);
}
}
drupal_json_output($results);
}
function MY_MODULE_form_alter(&$form, &form_state) {
$form['contact'] = array(
'#type' => 'textfield',
'#title' => t('Contact'),
'#maxlength' => 60,
'#autocomplete_path' => 'MY_MODULE/redhen/contact/autocomplete',
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment