Here are some code snippets to update field values programmatically.
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)
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
$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.
drupal 8