4

I want to get all taxonomy term in $lang language, following snippet works correctly and return all terms of $lang code.

    $query = \Drupal::entityQuery('taxonomy_term');
    $query->condition('vid', "news_category");
    $query->condition('langcode', $lang);
    $tids = $query->execute();
    //$terms = \Drupal\taxonomy\Entity\Term::loadMultiple($tids);
    return new JsonResponse($tids);

Then I want get results in order that in the taxonomy list they are, try to sort them with $query->sort('weight','ASC'); but with following snippet the results are the same before adding sort.

    $query = \Drupal::entityQuery('taxonomy_term');
    $query->condition('vid', "news_category");
    $query->condition('langcode', $lang);
    $query->sort('weight','ASC');
    $tids = $query->execute();
    //$terms = \Drupal\taxonomy\Entity\Term::loadMultiple($tids);
    return new JsonResponse($tids);

Does anybody know where the problem is? How can I get terms in order they are in taxonomy list?

2 Answers 2

5

Taxonomy overview list uses something like:

  ->sort('weight', 'ASC')
  ->sort('name', 'ASC')

If that doesn't work for you, take a look at \Drupal\taxonomy\TermStorage::loadTree

3
  • 1
    thansk for your attention, but not worked
    – Yuseferi
    Mar 13, 2017 at 21:33
  • 1
    in my question I write down sort by weight, adding another sort by name couldn't help. This is not WORKS
    – Yuseferi
    Mar 14, 2017 at 19:05
  • I confirm that it works for a flat list only. Oct 20, 2021 at 16:47
3

As was previously suggested, taking a look at \Drupal\taxonomy\TermStorage::loadTree is helpful. Entity Query only provides access to properties of the entity and its Field API values. Since the weight of the term is available in the taxonomy_term_field_data table, it will be available to entityQuery as well. However, any nesting of terms, aka hierarchy, will require access to the taxonomy_term_hierarchy table. That would require a database query.

You can access it via a database query, as seen in loadTree, line 204:

    $query = \Drupal::database()->select('taxonomy_term_field_data', 't');
    $query->join('taxonomy_term_hierarchy', 'h', 'h.tid = t.tid');
    $result = $query
      ->addTag('taxonomy_term_access')
      ->fields('t')
      ->fields('h', array('parent'))
      ->condition('t.vid', $vid)
      ->condition('t.default_langcode', 1)
      ->orderBy('t.weight')
      ->orderBy('t.name')
      ->execute();

I have updated the query to use Drupal's container, rather than the dependency injection so it can be used more readily. You should be able to modify this to fit your needs if Entity Query is not working as you desire it to.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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