Skip to content

Instantly share code, notes, and snippets.

@Erikdekamps
Last active May 27, 2021 12:56
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save Erikdekamps/740c82ccb0fc4ee178287ff0c2eafc92 to your computer and use it in GitHub Desktop.
Save Erikdekamps/740c82ccb0fc4ee178287ff0c2eafc92 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