1 entityreference.module entityreference_autocomplete_callback_get_matches($type, $field, $instance, $entity_type, $entity_id = '', $string = '')

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 definition.

$instance: The instance array definition.

$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.

File

core/modules/entityreference/entityreference.module, line 1043
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($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.
    // Only autocomplete the last tag.
    $tags_typed = backdrop_explode_tags($string);
    $tag_last = backdrop_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 = $instance['widget']['settings']['hide_ids'] ? $label : "$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>';
      }
    }
  }

  backdrop_json_output($matches);
}