function entityreference_autocomplete_callback_get_matches in Entity reference 7
Return JSON based on given field, instance and string.
This function can be used by other modules that wish to pass a mocked definition of the field on instance.
Parameters
$type: The widget type (i.e. 'single' or 'tags').
$field: The field array defintion.
$instance: The instance array defintion.
$entity_type: The entity type.
$entity_id: Optional; The entity ID the entity-reference field is attached to. Defaults to ''.
$string: The label of the entity to query by.
1 call to entityreference_autocomplete_callback_get_matches()
- entityreference_autocomplete_callback in ./
entityreference.module - Menu callback: autocomplete the label of an entity.
File
- ./
entityreference.module, line 1078 - Entityreference primary module file.
Code
function entityreference_autocomplete_callback_get_matches($type, $field, $instance, $entity_type, $entity_id = '', $string = '') {
$matches = array();
$prefix = '';
$entity = NULL;
if ($entity_id !== 'NULL') {
$entity = entity_load_single($entity_type, $entity_id);
$has_view_access = entity_access('view', $entity_type, $entity) !== FALSE;
$has_update_access = entity_access('update', $entity_type, $entity) !== FALSE;
if (!$entity || !($has_view_access || $has_update_access)) {
return MENU_ACCESS_DENIED;
}
}
$handler = entityreference_get_selection_handler($field, $instance, $entity_type, $entity);
if ($type == 'tags') {
// The user enters a comma-separated list of tags.
// We only autocomplete the last tag.
$tags_typed = drupal_explode_tags($string);
$tag_last = drupal_strtolower(array_pop($tags_typed));
if (!empty($tag_last)) {
$prefix = count($tags_typed) ? implode(', ', $tags_typed) . ', ' : '';
}
}
else {
// The user enters a single tag.
$tag_last = $string;
}
if (isset($tag_last)) {
// Get an array of matching entities.
$entity_labels = $handler
->getReferencableEntities($tag_last, $instance['widget']['settings']['match_operator'], 10);
$denied_label = t(ENTITYREFERENCE_DENIED);
// Loop through the products and convert them into autocomplete output.
foreach ($entity_labels as $values) {
foreach ($values as $entity_id => $label) {
// Never autocomplete entities that aren't accessible.
if ($label == $denied_label) {
continue;
}
$key = "{$label} ({$entity_id})";
// Strip starting/trailing white spaces, line breaks and tags.
$key = preg_replace('/\\s\\s+/', ' ', str_replace("\n", '', trim(decode_entities(strip_tags($key)))));
// Names containing commas or quotes must be wrapped in quotes.
if (strpos($key, ',') !== FALSE || strpos($key, '"') !== FALSE) {
$key = '"' . str_replace('"', '""', $key) . '"';
}
$matches[$prefix . $key] = '<div class="reference-autocomplete">' . $label . '</div>';
}
}
}
drupal_json_output($matches);
}