Score:1

Programmatically verify a taxonomy term has been added to a node

fr flag

I'm currently checking the node type and status, using the following code.

$query = \Drupal::entityQuery('node')
  ->condition('status', 1)
  ->condition('type', 'content_page')
  ->execute();

foreach ($query as $nid) {
  // …
}

I need to know whether a taxonomy term has been added to a node. I don't need to know the name or ID of that term, which is a taxonomy term from the Group Required vocabulary.

What code should I use to achieve this?

Score:2
in flag

Since you know that your tag will always be in one specific field, you can use the exists() method on your query to only fetch ids of entities where that field has a value, i.e. is not empty.

For example:

$entity_ids = \Drupal::entityTypeManager()
  ->getStorage('node')
  ->getQuery()
  ->condition('type', 'content_page')
  ->condition('status', 1)
  // Check if field has a non empty value
  ->exists('MY_TAXONOMY_REF_FIELD')
  // exists('MY_FIELD') is equivalent to condition('MY_FIELD', NULL, 'IS NOT NULL')
  ->execute();

Then, load your entities:

$entities = \Drupal::entityTypeManager()
  ->getStorage('node')
  ->loadMultiple($entity_ids);
RepublicOfDavid avatar
fr flag
Brilliant, works a treat, many thanks sonfd :-)
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.