4

I need to change a field in a node without altering the 'changed' timestamp. I know this was possible in Drupal 7 using field_attach_update(), but that has been removed since then.

I could use an update query and change the field directly in the database, but I was wondering if there is a better way (or a replacement for field_attach_update()).

1
  • I would suggest looking for a different approach here. changed is a system field that reflects the last time that the node was saved. You might consider having a secondary field that you use to track the last time the node was updated "for real", as there isn't a way to bypass the changed field that I'm aware of. Can you provide the reason WHY you're wanting to do this? Are you trying to track the number of times a node was viewed? If so I would recommend tracking node views on something other than the node.
    – lukedekker
    Jan 22, 2019 at 22:19

2 Answers 2

1

The functionality is available on SqlContentEntityStorage but it's protected. Bother! said Pooh and reflected on his poor Drupal coding practices:

    $storage = $this->entityTypeManager->getStorage($entity->getEntityType());
    if ($storage instanceof SqlContentEntityStorage) {
      // assemble the list of fields you want to save in $names.
      (new \ReflectionObject($storage))
        ->getMethod('doSaveFieldItems')
        ->invoke($storage, $entity, $names);
      $storage->resetCache([$entity->id()]);
    }
0

Let's try this code:

function MODULE_NAME_node_presave(Drupal\node\NodeInterface $node) {
  $node->set('FIELE_NAME', 'FIELD_VALUE');
}

OR

use Drupal\node\NodeInterface;

function hook_entity_presave(Drupal\Core\Entity\EntityInterface $entity)   {
  if ($entity instanceof NodeInterface) {
    $entity->title->value = 'testing';
  }
}
3
  • that would work if i'm saving the node, but i am not saving the node, i am loading it
    – diesonne
    Oct 31, 2016 at 8:41
  • @diesonne You should add in the question you are loading the node. It is not clear you don't want to save the node, since you are saying that you need to change a field, and then you talk of database.
    – apaderno
    Apr 20, 2017 at 9:16
  • @kiamlaluno when you save the node, the timestamps are updated. That's what i'm trying to prevent. Even when you use presave hooks the timestamp is still altered regardless of what value I set for the timestamps
    – diesonne
    Apr 20, 2017 at 9:45

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.