Last active
May 27, 2021 12:56
-
-
Save Erikdekamps/740c82ccb0fc4ee178287ff0c2eafc92 to your computer and use it in GitHub Desktop.
Drupal 8 - Load taxonomy terms sorted by weight
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Get taxonomy terms sorted by weight. | |
* | |
* @param int $vid | |
* The vocabulary id. | |
* | |
* @return array | |
* Returns an array of term id | name. | |
* | |
* @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException | |
* @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException | |
*/ | |
private function getTaxonomyTermsSortedByWeight($vid) { | |
// Initialize the items. | |
$items = []; | |
// Get the term storage. | |
$entity_storage = $this->entityTypeManager->getStorage('taxonomy_term'); | |
// Query the terms sorted by weight. | |
$query_result = $entity_storage->getQuery() | |
->condition('vid', $vid) | |
->sort('weight', 'ASC') | |
->execute(); | |
// Load the terms. | |
$terms = $entity_storage->loadMultiple($query_result); | |
foreach ($terms as $term) { | |
$items[$term->id()] = $term->getName(); | |
} | |
// Return the items. | |
return $items; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment