Drupal - How do I programmatically set a taxonomy term for a node?

In Drupal 7, taxonomy reference fields existed which used the pattern ['tid' => NUMBER]. These are entity reference fields. The EntityReferenceItem has the property definitions: target_id and entity. The former is a either an integer or string depending on the entity reference item's settings (basically config/content entity type).

This is also a similar question to How to set value for multivalue field in drupal 8 programmatically

So try to use the pattern

As part of Entity::create

Node::create([
  'field_meldungstyp' => [['target_id' => 19]]
]);

Using FieldableEntityInterface::set

$entity->set('field_meldungstyp', ['target_id' => 19]);

Using TypedDataInterface::setValue on the field item directly.

$entity->field_meldungstyp->setValue(['target_id' => 19]);

With magic method

$entity->field_meldungstyp->target_id = 19;

Note that this overwrites any current values of the field.


It needs to be a nested array.

'field_meldungstyp'  => [
      ['target_id' => 12345]
    ]

Try this:

$node = Node::create(array(
    'type' => 'detailseite',
    'title' => $data[$headlineIndex],
    'langcode' => 'de',
    'uid' => '1',
    'status' => 1,
    'field_headline' => $data[$headlineIndex],
    'field_intro' => $data[$introIndex] . $categories[$data[$categoryIndex]],
    'created' => $data[$dateIndex],
    'field_autor' => $data[$autorIndex],
    'field_teaser_text' => $data[$shortIndex],
    'field_meldungstyp'  => [
      ['target_id' => 12345]
    ]
));
$node->save();

Here is how i did it for D8.

use Drupal\node\Entity\Node;

//To create new node
$node = Node::create(['type' => 'YOUR_CONTENT_TYPE_HERE']);

//To load a node by its ID
//$node = \Drupal\node\Entity\Node::load(NODE_ID);

$nodeTerms = [1,2,3...]; // 1,2,3 = terms IDs
$node->set('YOUR_FIELD_OF_TERMS', $nodeTerms);
$node->save();

//To create new tax

use Drupal\taxonomy\Entity\Term;

$new_term = Term::create([
    'vid' => "YOUR_VOCABULARY_MACHINE_NAME",
    'name' => "NAME_OF_YOUR_TERM",
]);
$new_term->save();