You are here

function entity_autocomplete in Entity Autocomplete 7

Autocomplete callback for all entity types.

3 string references to 'entity_autocomplete'
EntityAutocompleteWebTestCase::setUp in tests/entity_autocomplete.test
Sets up a Drupal site for running functional and integration tests.
EntityAutocompleteWebTestCase::testAutocompleteElement in tests/entity_autocomplete.test
Tests FAPI element.
entity_autocomplete_menu in ./entity_autocomplete.module
Implements hook_menu().

File

./entity_autocomplete.module, line 55
Provides functionalities for entity fields autocompletion.

Code

function entity_autocomplete($string, $entity_type, $bundles = NULL) {
  $info = entity_get_info($entity_type);
  $table = $info['base table'];
  $matches = array();
  if (drupal_strlen($string)) {
    $query = db_select($table);
    $query
      ->addField($table, $info['entity keys']['id'], 'id');
    $query
      ->addField($table, $info['entity keys']['label'], 'label');
    $query
      ->condition($info['entity keys']['label'], '%' . db_like($string) . '%', 'LIKE');
    if ($bundles) {
      $bundle_field = $info['entity keys']['bundle'];
      if ($entity_type == 'taxonomy_term') {
        $vids = array_map(create_function('$v', 'return $v->vid;'), taxonomy_vocabulary_get_names());
        $bundles = array_intersect_key($vids, array_flip($bundles));
        $bundle_field = 'vid';
      }
      $query
        ->condition($bundle_field, $bundles);
    }
    $result = $query
      ->execute();
    while ($entity = $result
      ->fetch()) {
      $label = entity_autocomplete_get_label($entity->label, $entity->id);
      $matches[$label] = $label;
    }
  }
  drupal_json_output($matches);
}