6

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?

9

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.

  • Nice, haven’t sent that one before – Clive Nov 15 '17 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 '17 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! – 4k4 Nov 16 '17 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 '17 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. – 4k4 Nov 17 '17 at 10:31

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.