Drupal - How do I change a field with hook_node_presave()?

A bit outdated but still a great resource:


Also the documentation on drupal.org: https://www.drupal.org/node/1795854

In short, fields are lists of objects that use property and array access magic methods to simplify reading and writing values to them:

// Set a value, the field class will decide what to do with it, usually write to the primary property...
$entity->field_fieldname = importantfunction();

// The default property is often called value, but for reference fields, it is target_id, text fields also have a format for example
$entity->field_fieldname->format = 'full_html';

// By default, you access delta 0, you can also set other deltas.
$entity->field_fieldname[1] = importantfunction();

// You can also append a new item, without hardcoding the delta.

// Note that when accessing fields, you must always specify the property:
print $entity->field_fieldname->value;
print $entity->field_fieldname[1]->value;

// What basically happens internally for the above is:

Probably late here but if anyone is still looking then:

function mymodule_entity_presave(EntityInterface $entity){
    $entity->set( 'field_fieldname',importantfunction() );