function entityreference_autocomplete_callback in Entity reference 8
Same name and namespace in other branches
- 7 entityreference.module \entityreference_autocomplete_callback()
Menu callback: autocomplete the label of an entity.
Parameters
$type: The widget type (i.e. 'single' or 'tags').
$field_name: The name of the entity-reference field.
$entity_type: The entity type.
$bundle_name: The bundle name.
$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 string reference to 'entityreference_autocomplete_callback'
- entityreference_menu in ./
entityreference.module - Implements hook_menu().
File
- ./
entityreference.module, line 397 - Provides a field that can reference other entities.
Code
function entityreference_autocomplete_callback($type, $field_name, $entity_type, $bundle_name, $entity_id = '', $string = '') {
$field = field_info_field($field_name);
$instance = field_info_instance($entity_type, $field_name, $bundle_name);
$matches = array();
$target_type = $field['settings']['target_type'];
$entity = NULL;
if ($entity_id !== 'NULL') {
$entity = entity_load($entity_type, $entity_id);
// TODO: Improve when we have entity_access().
$entity_access = $target_type == 'node' ? node_access('view', $entity) : TRUE;
if (!$entity || !$entity_access) {
return MENU_ACCESS_DENIED;
}
}
$handler = entityreference_get_selection_handler($field, $instance, $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.
$prefix = '';
$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);
// Loop through the products and convert them into autocomplete output.
foreach ($entity_labels as $entity_id => $label) {
$key = "{$label} ({$entity_id})";
// Strip things like 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>';
}
}
return new JsonResponse($matches);
}