You are here

function shs_term_load_all_parents in Simple hierarchical select 8

Same name and namespace in other branches
  1. 2.0.x shs.module \shs_term_load_all_parents()

Helper function to load only a single ancestry for a given term.

A single ancestry is needed because for terms with multiple parents, the hierarchy cannot be determined.

@todo Remove this when https://www.drupal.org/node/2793243 lands.

Parameters

int $tid: The taxonomy term ID.

string $target_type: The entity type. Defaults to 'taxonomy_term'.

Return value

array An array of term parents.

See also

\Drupal\taxonomy\TermStorage::loadAllParents

1 call to shs_term_load_all_parents()
WidgetDefaults::getParentDefaults in src/WidgetDefaults.php
Load parents for default values.

File

./shs.module, line 92
Main functions and methods for the "Simple hierarchical select" module.

Code

function shs_term_load_all_parents($tid, $target_type = 'taxonomy_term') {
  $parents_all =& drupal_static(__FUNCTION__, []);
  if (!isset($parents_all[$tid])) {
    $parents = [];

    /** @var \Drupal\taxonomy\TermStorageInterface $storage */
    $storage = \Drupal::entityTypeManager()
      ->getStorage($target_type);
    if ($term = $storage
      ->load($tid)) {
      $parents[$term
        ->id()] = $term;
      $terms_to_search[] = $term
        ->id();
      while ($tid = array_shift($terms_to_search)) {
        if ($new_parents = $storage
          ->loadParents($tid)) {

          // Here, only take the first parent found. This differs from
          // the `loadAllParents` method.
          if ($new_parent = reset($new_parents)) {
            if (!isset($parents[$new_parent
              ->id()])) {
              $parents[$new_parent
                ->id()] = $new_parent;
              $terms_to_search[] = $new_parent
                ->id();
            }
          }
        }
      }
    }
    $parents_all[$tid] = $parents;
  }
  return $parents_all[$tid];
}