How to programmatically update a field's value in Drupal 8

You, DrupalDrupal field
Back

Following are the code snipped to update field values programmatically. Number of different ways are discussed and feel free to comment if anything is missing.

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
}

or you can always load the node and update it

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

If there are more attributes you can use

$node->FIELD_NAME->target_id = $tid;

So for example to update taxonomy reference from a node (Assume we have field_tags exists)

$node->field_tags->target_id = $tid;

Multivalue fields

Add an item to a multivalue field:

$node->FIELD_NAME[] = ['target_id' => $tid];

The property target_id is not necessary, because it is the main property and used by default. So for most fields you can add a value like in a simple php array, which is easy to remember:

$node->FIELD_NAME[] = $tid;
© Heshan Wanigasooriya.RSS

🍪 This site does not track you.