首页 > 解决方案 > 如何更新 hook_presave 上的实体翻译?

问题描述

保存时,我需要更新节点上的字段值。我正在使用 hook_entity_presave 来获取值并更新节点保存上的字段。

但我想在该节点的所有语言翻译中更新该字段,但它只更新主要语言('en')节点。

$node = Node::load($cid);
if (empty($node)) {
  return FALSE;
}
$node->set('field_ship_name', $name);
$node = $node->save();

我在这里先向您的帮助表示感谢。

标签: drupalentitytranslation

解决方案


尝试这个:

$node = Node::load($cid);
if (empty($node)) {
  return FALSE;
}
$languages = $node->getTranslationLanguages($include_default = TRUE);
foreach($languages as $lang) {
  $node_translation = \Drupal::service('entity.repository')->getTranslationFromContext($node, $lang);
  $node_translation->set('field_ship_name', $name);
  $node_translation = $node_translation->save();
}

推荐阅读