Score:2

hook_node_presave get original of translated node

cn flag

I'm using a hook_node_presave and I want to detect which field is updated when the translated node is updated. Here is my code :

function hook_import_node_presave(\Drupal\node\NodeInterface $node) {
  if (!$node->isNew()){
    $entityFieldManager = \Drupal::service('entity_field.manager');
    $fields = $entityFieldManager->getFieldDefinitions('node', 'article');
    foreach($fields as $field_name => $field_definition) {
      foreach ($node->getTranslationLanguages() as $langcode => $langcode_value) {
        $node = $node->getTranslation($langcode);
        if ($node->get($field_name)->getValue() != $node->original->get($field_name)->getValue()) {
          // do something
        }
      }
    }
  }
}

However,

$node = $node->getTranslation($langcode);
$node->original->get($field_name)->getValue()

even after "getTranslation()", "original" is still pointing to the default language. I want to get the "original" language of the translated node.

4uk4 avatar
cn flag
What is the result of $node->original->getTranslation($langcode)->get($field_name)->getValue()?
Gabriel Fernandez avatar
cn flag
Yes! Seems like it is now getting the "original" value of the translated node. Thank you so much!
Score:1
cn flag
$node = $node->getTranslation($langcode);

This is changing the translation of the node object passed by reference. Better use a different variable:

$node_translated = $node->getTranslation($langcode);

$node->original->get($field_name)->getValue()

original is a separate node object and has to be translated separately:

$node->original->getTranslation($langcode)->get($field_name)->getValue()
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.