3

I know I can get list of of taxonomy of a vocabulary with

 $terms =  \Drupal::entityManager()->getStorage('taxonomy_term')->loadTree('course_category');

 kint($terms);

but it returned all that vocabulary terms, I am working on multi language site,I want retrieve terms of specified language.

my Drupal version is 8.1.3

  • did u pass vid of a particular vocabulary term u wanted to retrieve ?? – Shreya Shetty Jun 21 '16 at 7:38
  • yes ,but it return all of terms,` $terms = \Drupal::entityManager()->getStorage('taxonomy_term')->loadTree('course_category'); ` . I just limit to specified language – Yusef Jun 21 '16 at 7:39
  • Are you using any module for translation?? – Shreya Shetty Jun 21 '16 at 8:00
  • @ShreyaShetty drupal8 build-in support multi language. – Yusef Jun 21 '16 at 8:39
  • Do you care about the tree structure provided by the loadTree method, or do you just want to load all the terms of said language? – Eyal Jun 21 '16 at 19:51
3

I had some difficulties with printing tags in the current language in code too. This is what worked to get ONLY the translated terms of a vocabulary:

$vocabulary = 'MY_VOCABULARY_NAME';
$language =  \Drupal::languageManager()->getCurrentLanguage()->getId();
$query = \Drupal::entityQuery('taxonomy_term');
$query->condition('vid', $vocabulary);
$query->sort('weight');
$tids = $query->execute();
$terms = \Drupal\taxonomy\Entity\Term::loadMultiple($tids);
$termList = array();

foreach($terms as $term) {
    if($term->hasTranslation($language)){
        $tid = $term->id();
        $translated_term = \Drupal::service('entity.repository')->getTranslationFromContext($term, $language);
        $termList[$tid] = $translated_term->getName();
    }
}

// To print a list of translated terms. 
foreach($termList as $tid => $name) {
     print $name;
}

To link the tags, see https://drupal.stackexchange.com/a/243160/71941

1

You can use the loadByProperties method to load all the entities that their fields correspond to certain values.

For a more advance selection you can use the entity query service.

\Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadByProperties([
  'vid' => $vid,
  'language' => $language_id
]);
  • I had to use langcode as the property key. Note that this will only return terms that actually have a translation. – Tim Sep 9 at 14:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.