2

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.

2
  • 1
    What is the result of $node->original->getTranslation($langcode)->get($field_name)->getValue()?
    – 4uk4
    Commented Nov 14, 2021 at 14:39
  • Yes! Seems like it is now getting the "original" value of the translated node. Thank you so much! Commented Nov 15, 2021 at 0:16

1 Answer 1

1
$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()

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.