Skip to content

Instantly share code, notes, and snippets.

@manojiksula
Forked from Erikdekamps/module.install
Created May 27, 2021 12:56
Show Gist options
  • Save manojiksula/2bf5cf1fa8231ab254d370c965e4ca28 to your computer and use it in GitHub Desktop.
Save manojiksula/2bf5cf1fa8231ab254d370c965e4ca28 to your computer and use it in GitHub Desktop.
Drupal 8 - Load taxonomy terms sorted by weight
/**
* 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