Score:0

Translating Menu Item Programmatically?

pk flag

I have been trying to translate menu items programmatically but upon saving it just adds the english field value to all my translations. Below is the code I am trying to execute:

 if ($entity->hasTranslation($language->getId())) {
      //For update
      $entity->removeTranslation($language->getId());
    }
    try {
      $entity->addTranslation($language->getId(), ['title' => 'abcd'])->save();
    } catch (EntityStorageException $e) {
      \Drupal::logger('Menu-Translation')->error($e->getMessage());
      \Drupal::messenger()->addError(t('Failed to add translation for ' . $language->getName()));
    }

I am debugging and I think the issue lies in the line :

$entity->addTranslation($language->getId(), ['title' => 'abcd'])->save();

Any help would be appreciated. Thankyou.

cn flag
Just a sanity check - is the "Menu link title" field configured to be translatable at /admin/config/regional/content-language?
blur avatar
bn flag
How are you implementing localization? Menu items should have a 'translate' link (or something similar) in the menu UI (structure -> menus).
Score:1
de flag

You didn't take into account the default language. Your code will break if you're running this code on a callback in the default language, because you remove the default translation, and you're not allowed to do that:

$defaultLanguage = \Drupal::languageManager->getDefaultLanguage()->getId();
if ($entity->hasTranslation($language->getId()) && $language->getId() !== $defaultLanguage) {
  // For update
  $entity->removeTranslation($language->getId());
}
try {
  if ($language->getId() === $defaultLanguage) {
    // Just set the field value, not the translation:
    $entity->set('title', 'abcd');
  }
  else {
    $entity->addTranslation($language->getId(), ['title' => 'abcd'])->save();
  }
} catch (EntityStorageException $e) {
  \Drupal::logger('Menu-Translation')->error($e->getMessage());
  \Drupal::messenger()->addError(t('Failed to add translation for ' . $language->getName()));
}
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.