0

I have a code which is running in hook_node_update. This code grab the revision of the saved node and compare the values of the fields between current node and its revision to generate some kind of historic log (what is deleted/updated/added).

This is working very well except for the paragraph field... When my code is trying to get the revision of a paragraph (recursively), I got each time the same paragraph instead of the old revision (thus no differences to log)

Here is my code to get the revision of a the saved node (working well). This code is also used for the paragraphs (not working)

$updated_entity : the node/paragraph currently in the process to be saved

$old_entity : the revision to compare with

  $old_entity = $updated_entity->original;
  if (!$old_entity) {
    $storage = $this->getStorage($updated_entity);
    // no need to test if revisionable as we use only Node and Paragraphs
    if ($revision_id = $updated_entity->getLoadedRevisionId()) {
      $old_entity = $storage->loadRevision($revision_id);
     }
    else {
      //... handling new entity
      ]);
    }
  }

This code, when applied to the paragraphs, is producing an $old_entity == $updated_entity

The paragraphs are extracted from the currently saved node as follow:

$paragraphs = $updated_entity->get($paragraph_field)->referencedEntities();

after that, they become the $updated_entity variable in the upper function which is trying to get the revision...

1

The unnamed upper function works only for the one specific node you get via the hook as parameter. Load the old referenced paragraphs via the original entity:

$old_paragraphs = $node->original->get($paragraph_field)->referencedEntities();

For nested paragraphs you can then apply recursive loading, but each branch (old/new) separately and not with the upper function, use ->referencedEntities() for mulitple and ->entity for single field items, these functions load revisions.

In a multilingual site you have to get the translation of the paragraph using the node language:

$node_language = $node->language()->getId();
$value = $paragraph->getTranslation($node_language)->field_foo->value;
1
  • Comments are not for extended discussion; this conversation has been moved to chat.
    – Clive
    Nov 22 '21 at 17:29

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.