-1

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

1
  • 1
    I'll ask the obvious - are you saving the node?
    – Kevin
    May 13, 2022 at 11:42

1 Answer 1

1

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();

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.