Score:-1

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;
    if(empty($termIds)){
      return NULL;
    }
  
    $query = \Drupal::database()->select('taxonomy_index', 'ti');
    $query->fields('ti', array('nid'));
    $query->condition('ti.tid', $termIds, 'IN');
    $query->distinct(TRUE);
    $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])
$node->field_news_categories->setValue($termID)
$node->field_news_categories->setValue(array($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:

$node->field_news_categories->getValue()
$node->get('field_news_categories')->getValue()
$node->field_news_categories->value
$node->get('field_news_categories')->value
$node->field_news_categories
$node->get('field_news_categories')
$node->get('field_news_categories')->target_id
$node->get('field_news_categories')->entity
$node->get('field_news_categories')->referencedEntities()

Project is in drupal 9

Kevin avatar
in flag
I'll ask the obvious - are you saving the node?
Score:1
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.

$node->save();
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.