You are here

function farm_fields_autocomplete in farmOS 7

Page callback for the farm fields autocomplete callback.

Parameters

string $entity_type: The entity type.

string $bundle: The entity bundle.

$field_name: The field name.

string $string: The string to search for.

2 string references to 'farm_fields_autocomplete'
farm_fields_autocomplete_menu in modules/farm/farm_fields/farm_fields_autocomplete/farm_fields_autocomplete.module
Implements hook_menu().
farm_update_7049 in ./farm.install
Enable Farm Fields Autocomplete module.

File

modules/farm/farm_fields/farm_fields_autocomplete/farm_fields_autocomplete.module, line 38
Farm fields autocomplete module.

Code

function farm_fields_autocomplete($entity_type, $bundle, $field_name, $string) {

  // Create an entity field query to find matching entities.
  $query = new EntityFieldQuery();
  $query
    ->entityCondition('entity_type', $entity_type);
  $query
    ->entityCondition('bundle', $bundle);
  $query
    ->fieldCondition($field_name, 'value', '%' . $string . '%', 'LIKE');
  $query
    ->fieldOrderBy($field_name, 'value', 'ASC');
  $query
    ->range(0, 10);

  // Execute the query to get entity IDs.
  $entity_ids = array();
  $result = $query
    ->execute();
  if (isset($result[$entity_type])) {
    $entity_ids = array_keys($result[$entity_type]);
  }

  // Only include entities that the user has access to.
  $entities = array();
  foreach ($entity_ids as $id) {
    $entity_load = entity_load($entity_type, array(
      $id,
    ));
    $entity = reset($entity_load);
    if (!entity_access('view', $entity_type, $entity)) {
      continue;
    }
    $entities[] = $entity;
  }

  // If there are entities, iterate through them and build a list of matches.
  $matches = array();
  if (!empty($entities)) {
    foreach ($entities as $entity) {
      if (!empty($entity->{$field_name}[LANGUAGE_NONE])) {
        foreach ($entity->{$field_name}[LANGUAGE_NONE] as $item) {
          if (!empty($item['value']) && strpos(strtolower($item['value']), strtolower($string)) !== FALSE) {
            if (!in_array($item['value'], $matches)) {

              // We use htmlspecialchars() instead of check_plain() to preserve
              // single quotes (apostrophes).
              $matches[] = htmlspecialchars($item['value']);
            }
          }
        }
      }
    }
  }

  // Map to an associative array.
  $matches = drupal_map_assoc($matches);

  // Return the matches as JSON.
  drupal_json_output($matches);
}