4

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 ) {
        $node->values['field_fieldname'][0]['value'];
    } 
}

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.

3

A bit outdated but still a great resource:

http://wizzlern.nl/drupal/drupal-8-entity-cheat-sheet

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.
$entity->field_fieldname->appendItem(importantfunction());

// 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:
$entity->get('field_fieldname')->get(0)->get('value')->getValue();
| improve this answer | |
  • That's much better! – ndvo Nov 9 '15 at 19:36
3

Probably late here but if anyone is still looking then:

function mymodule_entity_presave(EntityInterface $entity){
    $entity->set( 'field_fieldname',importantfunction() );
}
| improve this answer | |
0

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() );
}
| improve this answer | |
0

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');
    }
}
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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