8

Currently I am firstly "searching" for an taxonomy term entity with the Entity Query in Drupal 8:

$termIds = \Drupal::entityQuery('taxonomy_term')
  ->condition('field_code', $code)
  ->condition('vid', 'computer')
  ->execute();

And then I am loading the taxonomy term entity:

      $termId = current($termIds);
      $term = \Drupal::entityTypeManager()
        ->getStorage('taxonomy_term')
        ->load($termId);

Is there a way to do it in 1 step, instead of these two?

1 Answer 1

15

You can do this in one step by using loadByProperties():

$term = current(\Drupal::entityTypeManager()->getStorage('taxonomy_term')
  ->loadByProperties(['field_code' => $code, 'vid' => 'computer'])
);

This method is a shortcut for basic entity queries like you have here and also includes the step for loading the entities.

5
  • Nice, haven’t sent that one before
    – Clive
    Nov 15, 2017 at 15:03
  • I have tried it with an node title and this does not work: current(\Drupal::entityTypeManager()->getStorage('node') ->loadByProperties( [ 'title' => $title, 'type' => 'authority' ] ) );
    – jepster
    Nov 15, 2017 at 20:17
  • Your code is OK. I've put in a title and type from a node I have on my site and it worked!
    – 4uk4
    Nov 16, 2017 at 7:26
  • I have tested it again. And again it does not work. I have wrote a method to shorten this up: private function loadNodeByProperties(array $conditions) { $query = \Drupal::entityTypeManager()->getStorage('node')->getQuery(); foreach ($conditions as $field => $value) { $query->condition($field, $value); } return Node::load(current($query->execute())); }
    – jepster
    Nov 17, 2017 at 10:21
  • yes, this should work too, but loadByProperties() does the same: foreach ($values as $name => $value) { $entity_query->condition($name, (array) $value, 'IN'); }, only using 'IN' so that you could provide an array with multiple values.
    – 4uk4
    Nov 17, 2017 at 10:31

Your Answer

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

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