You are here

function uuidreference_autocomplete in UUID reference field 7

Autocomplete callback for uuidreference_autocomplete field widget.

Parameters

string $target_type:

string $string:

2 string references to 'uuidreference_autocomplete'
uuidreference_field_widget_form in ./uuidreference.module
Implements hook_field_widget_form().
uuidreference_menu in ./uuidreference.module

File

./uuidreference.module, line 432

Code

function uuidreference_autocomplete($entity_type, $bundle, $field_name, $string = '') {
  watchdog('acquia_entity', "{$string} has been searched for.");
  $field = field_info_field($field_name);
  $target_type = $field['settings']['target_type'];
  $entity_info = entity_get_info($target_type);

  // @todo This could also be title, but what else to assume if no label key is
  // present?
  $label_key = isset($entity_info['entity keys']['label']) ? $entity_info['entity keys']['label'] : 'name';
  $uuid_key = isset($entity_info['array keys']['uuid']) ? $entity_info['array keys']['uuid'] : 'uuid';
  $query = db_select($entity_info['base table'], 'base')
    ->fields('base', array(
    $uuid_key,
    $label_key,
  ))
    ->condition($label_key, '%' . db_like(trim($string)) . '%', 'LIKE')
    ->addTag($target_type . '_access')
    ->addTag('uuidreference')
    ->range(0, 15);

  // If there are any specified bundles, try to add those as a query condition.
  $target_bundles = array_filter(array_values($field['settings']['target_bundles']));
  if (!empty($target_bundles)) {
    $query
      ->condition($entity_info['entity keys']['bundle'], $field['settings']['target_bundles']);
  }

  // Invoke hook_uuidreference_autocomplete_query_alter() to allow other modules
  // to alter the autocomplete query based on entity_type, bundle, or field
  // context.
  module_invoke_all('uuidreference_autocomplete_query_alter', $query, $entity_type, $bundle, $field_name);
  $result = $query
    ->execute()
    ->fetchAllKeyed();
  $matches = array();
  if (!empty($result)) {

    // Loop through the products and convert them into autocomplete output.
    foreach ($result as $uuid => $label) {
      $label = check_plain($label);
      $key = "{$label} [{$uuid}]";

      // 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[$key] = $label;
    }
  }
  drupal_json_output($matches);
}