function TermStorage::getParents

Same name in other branches
  1. 8.9.x core/modules/taxonomy/src/TermStorage.php \Drupal\taxonomy\TermStorage::getParents()
  2. 10 core/modules/taxonomy/src/TermStorage.php \Drupal\taxonomy\TermStorage::getParents()
  3. 11.x core/modules/taxonomy/src/TermStorage.php \Drupal\taxonomy\TermStorage::getParents()

Returns a list of parents of this term.

@internal @todo Refactor away when TreeInterface is introduced.

Return value

\Drupal\taxonomy\TermInterface[] The parent taxonomy term entities keyed by term ID. If this term has a <root> parent, that item is keyed with 0 and will have NULL as value.

2 calls to TermStorage::getParents()
TermStorage::getAncestors in core/modules/taxonomy/src/TermStorage.php
Returns all ancestors of this term.
TermStorage::loadParents in core/modules/taxonomy/src/TermStorage.php
Finds all parents of a given term ID.

File

core/modules/taxonomy/src/TermStorage.php, line 130

Class

TermStorage
Defines a Controller class for taxonomy terms.

Namespace

Drupal\taxonomy

Code

protected function getParents(TermInterface $term) {
    $parents = $ids = [];
    // Cannot use $this->get('parent')->referencedEntities() here because that
    // strips out the '0' reference.
    foreach ($term->get('parent') as $item) {
        if ($item->target_id == 0) {
            // The <root> parent.
            $parents[0] = NULL;
            continue;
        }
        $ids[] = $item->target_id;
    }
    // @todo Better way to do this? AND handle the NULL/0 parent?
    // Querying the terms again so that the same access checks are run when
    // getParents() is called as in Drupal version prior to 8.3.
    $loaded_parents = [];
    if ($ids) {
        $query = \Drupal::entityQuery('taxonomy_term')->accessCheck(TRUE)
            ->condition('tid', $ids, 'IN');
        $loaded_parents = static::loadMultiple($query->execute());
    }
    return $parents + $loaded_parents;
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.