In my Drupal 8 project I have a menu containing menu items in english. Some of the items have a german translation. How do I filter the menu to only show the german items when viewing the site in german?
I'm currently using MenuLinkTree
to fetch my menu and I have created my own MenuLinkTreeManipulator
transform where I try to filter out MenuLinkContent items that does not have a translation in the current language. But the method for getting an entity from a MenuLinkContent
object is protected, so I cannot access the language property of the underlying entity!
Is there some other way of finding out the language of a MenuLinkContent object? Or another way of filtering a menu by current language?
Edit:
Here is the method I'm currently using (as a transform) when getting the menu via the MenuLinkTree
service:
public function currentLanguage($tree) {
$lang = \Drupal::languageManager()->getCurrentLanguage()->getId();
return array_filter($tree, function($item) use($lang) {
return $item->link->getEntity()->language()->getId() === $lang;
});
}
$item->link
above is an instance of \Drupal\menu_link_content\Plugin\Menu\MenuLinkContent
. The above code does not work since $item->link->getEntity()
is a protected method. If make it public the code above works. I see no way of accessing the underlying entity here without hacking core. Is it possible in any way? Is it possible to "swap" out this class for my own implementation in a custom module?