1

I am using Drupal 8. By retrieving an entity by Entity Query I am getting an array. How can I fetch directly the TID?

Right now I am doing the following:

  public function getCommuneTidByPostalCode(int $postalCode) {
    $commune = \Drupal::entityQuery('taxonomy_term')
      ->condition('field_zipcode', $postalCode)
      ->condition('vid', 'commune')
      ->execute();

    if (!empty($commune)) {
      return intval(key($commune));
    }
  }

Can I drop somehow this part?:

if (!empty($commune)) {
  return intval(key($commune));
}

1 Answer 1

4

No. An entity query always returns a list, if you want just one record, you have to get that from the array.

The intval() isn't really necessary though, Drupal/PHP doesn't care if you use the tid as string or integer. Also, it always returns an array, and key() also works on an empty array, so you can really simplify that to just return key($communie);. And I'd actually recommend to use current() or reset() because the key is the revision ID and the value the ID and while terms currently do not yet use revisions, they will likely soon support that.

So...

$commune = \Drupal::entityQuery('taxonomy_term')
  ->condition('field_zipcode', $postalCode)
  ->condition('vid', 'commune')
  ->execute();

return current($commune);

Is all you need.

0

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.