In Drupal 7, I was using hook_node_presave() to update some hidden fields in a node.

function mymodule_node_presave($node){
    if ( CONDITIONS ) {
        $node->field_fieldname['und'][0]['value'] = importantfunction();

In Drupal 8 I cannot do the same thing. Looking into the object I tried this:

function mymodule_node_presave($node){
    if ( CONDITIONS ) {

It won't work though. I am aware that a lot have changed in Drupal 8 and I am studying it, but I did not find an answer to this yet.

4 Answers 4


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:
  • That's much better!
    – ndvo
    Nov 9, 2015 at 19:36

Probably late here but if anyone is still looking then:

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

I don't know if this is a best practice, but I've come to this solution:

function mymodule_node_presave(EntityInterface $node){
    $node->field_fieldname->set(0, importantfunction() );

This is a very late answer.

With \Drupal\node\NodeInterface interface, I'm using that snippet to achieve your needs :

 * Implements hook_node_presave();
 * @param \Drupal\node\NodeInterface $node

function module_name_node_presave(\Drupal\node\NodeInterface $node) {
    if($node->get('field_name')->getString() != 'search') {
        $node->set('field_name', 'new field value');
  • This does not work
    – sea26.2
    Jun 17, 2020 at 3:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.