You are here

function select2widget_taxonomy_term_reference_get_matches in Select2 Field Widget 7.2

Return JSON based on given field, instance and string.

Parameters

$field: The field array defintion.

$instance: The instance array defintion.

$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

./select2widget.taxonomy.inc, line 147

Code

function select2widget_taxonomy_term_reference_get_matches($field, $instance, $entity_type, $string, $entity_id = '') {
  $voc_name = $field['settings']['allowed_values'][0]['vocabulary'];
  $settings = $instance['widget']['settings'][$instance['widget']['type']];
  $voc = taxonomy_vocabulary_machine_name_load($voc_name);
  $vid = (int) $voc->vid;
  $set_level = isset($settings['set_level']) && $settings['set_level'];
  $query = db_select('taxonomy_term_data', 't')
    ->fields('t', array(
    'tid',
    'name',
  ));
  if (module_exists('termstatus')) {
    $query
      ->leftJoin('termstatus', 's', 't.tid = s.tid');
    $query
      ->condition('s.status', 1);
  }
  if ($set_level) {
    $query
      ->leftJoin('taxonomy_term_hierarchy', 'h', 'h.parent = t.tid');
    $query
      ->condition('h.tid', NULL);
  }
  $query
    ->condition('t.vid', (int) $vid);
  if ($settings['match_limit']) {

    // NB match_limit only validates for integer, can include 0 and negative
    $query
      ->range(0, abs($settings['match_limit']));
  }
  else {
    $query
      ->range(0, 10);
  }
  if ($settings['match_operator'] === 'CONTAINS') {
    $query
      ->condition('t.name', '%' . $string . '%', 'LIKE');
  }
  else {
    $query
      ->condition('t.name', $string . '%', 'LIKE');
  }
  $results = $query
    ->execute()
    ->fetchAllAssoc('tid');
  $terms = array();
  if (!empty($results)) {
    $terms = taxonomy_term_load_multiple(array_keys($results));
  }
  $matches = array();
  $output = array();
  foreach ($terms as $term) {
    $parent = '';
    $output[$term->tid] = array(
      'name' => $term->name,
      'parent' => $parent,
    );
    $parents = taxonomy_get_parents_all($term->tid);
    $count = count($parents);
    for ($i = $count - 1; $i > 0; $i--) {
      $parent .= $parents[$i]->name;
      if ($i != 1) {
        $parent .= ' > ';
      }
    }
    if (!empty($parent)) {
      $output[$term->tid]['parent'] = ' (' . $parent . ')';
    }
  }
  foreach ($output as $tid => $term) {
    $matches[] = array(
      'id' => 'id' . chr(9) . $tid,
      'title' => $term['name'],
      'data' => '<div class="select2-taxonomy-term">' . $term['name'] . $term['parent'] . '</div>',
    );
  }
  drupal_json_output($matches);
}