Last active
June 21, 2016 15:40
-
-
Save wxactly/75cf2761379f17d9b0c4 to your computer and use it in GitHub Desktop.
Drupal Search API - Simple RedHen contact autocomplete
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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