Unable to add newly created term to the node

in flag

I want to add new taxonomy term to group of nodes that have specific terms already.

To retrive them I use this function

function getNodesByTaxonomyTermIds($termIds){
    $termIds = (array) $termIds;
      return NULL;
    $query = \Drupal::database()->select('taxonomy_index', 'ti');
    $query->fields('ti', array('nid'));
    $query->condition('ti.tid', $termIds, 'IN');
    $result = $query->execute();
    if($nodeIds = $result->fetchCol()){
      return Node::loadMultiple($nodeIds);
    return NULL;

then in foreach loop I'm adding im adding them to new term based on their creation date but adding does not work.

Here is my field structure:

Field structure

Firstly I tried all of those:

$node->set('field_news_categories', ['target_id' => $termID])
$node->set('field_news_categories', $termID)
$node->set('field_news_categories', array($termID))
$node->field_news_categories->setValue(['target_id' => $termID])

none worked so I thought maybe I should pass whole field with exact same structure, so I wanted to get field and just append the id and then pass it as argument in set method, but I wasn't able to get field either. All I was receving were null values or empty arrays. I tried:


Project is in drupal 9

Kevin avatar
in flag
I'll ask the obvious - are you saving the node?
cn flag

To append an entity reference item use:

$node->field_foo[] = ['target_id' => 123];

And as Kevin noted in the comments, make sure you save the entity.


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.