ctools_content_autocomplete_entity

  1. drupal
    1. 7 content.menu.inc function
Drupal 7 ctools_content_autocomplete_entity($type, $string = '')

Helper function for autocompletion of entity titles.

1 string reference to 'ctools_content_autocomplete_entity'

File

sites/all/modules/ctools/includes/content.menu.inc, line 26
Contains menu item registration for the content tool.

Code

function ctools_content_autocomplete_entity($type, $string = '') {
  $entity = entity_get_info($type);
  if ($string != '') {
    // @todo verify the query logic here, it's untested.
    // Set up the query
    $query = db_select($entity['base table'], 'b');
    if ($entity['entity keys']['label']) {
      $query->fields('b', array($entity['entity keys']['id'], $entity['entity keys']['label']))->range(0, 10);
    }
    else {
      $query->fields('b', array($entity['entity keys']['id']))->range(0, 10);
    }

    $preg_matches = array();
    $match = preg_match('/\[id: (\d+)\]/', $string, $preg_matches);
    if (!$match) {
      $match = preg_match('/^id: (\d+)/', $string, $preg_matches);
    }
    if ($match) {
      $query->condition('b.' . $entity['entity keys']['id'], $preg_matches[1]);
    }
    elseif ($entity['entity keys']['label']) {
      $query->condition('b.' . $entity['entity keys']['label'], '%' . db_like($string) . '%', 'LIKE');
    }

    $matches = array();
    if ($type == 'node') {
      $query->addTag('node_access');
      $query->join('users', 'u', 'b.uid = u.uid');
      $query->addField('u', 'name', 'name');

      foreach ($query->execute() as $nodeish) {
        $name = empty($nodeish->name) ? variable_get('anonymous', t('Anonymous')) : check_plain($nodeish->name);
        $matches[$nodeish->title . " [id: $nodeish->nid]"] = '<span class="autocomplete_title">' . check_plain($nodeish->title) . '</span> <span class="autocomplete_user">(' . t('by @user', array('@user' => $name)) . ')</span>';
      }
    }
    else {
      foreach ($query->execute() as $item) {
        $id = $item->{$entity['entity keys']['id']};
        if ($entity['entity keys']['label']) {
          $matches[$item->{$entity['entity keys']['label']} . " [id: $id]"] = '<span class="autocomplete_title">' . check_plain($item->{$entity['entity keys']['label']}) . '</span>';
        }
        else {
          $matches["[id: $id]"] = '<span class="autocomplete_title">' . check_plain($item->{$entity['entity keys']['id']}) . '</span>';
        }
      }
    }
    drupal_json_output($matches);
  }
}