Updating programmatically field(s) value(s) in Drupal 8 - Single or multiple values per field

May
2020
28
Here are some code snippets to update field values programmatically.
<?php
use Drupal\node\NodeInterface;
function
MODULE_NAME_node_presave($node) {
 
$node->setTitle('MY NEW TITLE'); // This is a special meta field
 
$node->set('FIELD_NAME', 'THIS IS DATA'); // This is a Field added in to the content type
 // $node->save is not needed with this hook
}?>
Loading and updating in code (*$node->save is needed here)
<?php
use Drupal\node\Entity\Node;
$node = Node::load($nid);
$node->setTitle('MY NEW TITLE'); // This is a special meta field
$node->set('FIELD_NAME', 'THIS IS DATA'); // This is a Field added in to the content type
$node->save();
?>
Entity Reference
$node->FIELD_NAME->target_id = $tid;
Multivalue fields
$node->FIELD_NAME[] = ['target_id' => $tid];
You can skip the "target_id" property because it is used by default (in this case). So this is valid too
$node->FIELD_NAME[] = $entity_id;
How to programmatically update an entity reference field with multiple or single value(s) in drupal 8
<?php
$term_tids
= [ '3','32','50'];
foreach(
$term_tids as $index => $tid) {
  if(
$index == 0) {
   
$node->set('field_article_term_ref', $tid);
  } else {
   
$node->get('field_article_term_ref')->appendItem([
     
'target_id' => $tid,
    ]);
  }
}
?>
With index == 0 we just check if the node already has a reference attached. If this is true we get the value, and we use the appendItem function.
Tags: 
Cats: 
this is an arrow pointing back to the top of the page