5

Hey I am loading a drupal 8 menu in the following way:

if ($menu != NULL) {
    $tree = \Drupal::menuTree()
    ->load("my_menu", new MenuTreeParameters());

This returns MenuLinkTreeElement objects. It does not seem possible to fetch the fields attached to the menu item.

How can I do that? Should I load the menu through another function?

11
  • $element->link should get you the entity which you can treat as any other wrt accessing field data
    – Clive
    May 8, 2017 at 13:34
  • I am trying that..it returns a MenuLinkContent but...this I can not use this to get any fields. I would think that I could get the uuid load the menu link entity and from there get the fields but even that is not possible, because the getUuid() is protected api.drupal.org/api/drupal/… May 8, 2017 at 13:38
  • 1
    MenuLinkContent is a content entity type; you can access its fields the same way as a node/taxonomy term/etc. e.g. $entity->field_foo->value
    – Clive
    May 8, 2017 at 13:45
  • I am trying to access the fields that I know for sure are there like title , but nothing comes back: $item->link->title->value May 8, 2017 at 14:03
  • 1
    Yep my mistake, that interface is a plugin interface. Looks like you're out of luck @Potney. For the obvious fields you're covered, e.g. $link->getTitle(), but the interface doesn't expose the data you're looking for. Might be worth posting a feature request, or looking at how modules like drupal.org/project/link_attributes solve similar problems
    – Clive
    May 8, 2017 at 14:47

1 Answer 1

12

You can get the menu link content entity by accessing the uuid with the method getDerivativeId() of the plugin:

if ($link instanceof \Drupal\menu_link_content\Plugin\Menu\MenuLinkContent) {
  $uuid = $link->getDerivativeId();
  $entity = \Drupal::service('entity.repository')
    ->loadEntityByUuid('menu_link_content', $uuid);
  $field_value = $entity->field_example->value;
}
5
  • EntityManager was deprecated, EntityRepository::loadEntityByUuid() seems to be a good alternative
    – Clive
    Dec 6, 2017 at 23:48
  • I remember I've checked this when writing the answer. Back then it was not used directly in core, now it pops up a few times. It's time to change this.
    – 4uk4
    Dec 7, 2017 at 7:34
  • This is so not-OO. There is a getEntity() function on \Drupal\menu_link_content\Plugin\Menu\MenuLinkContent but it is protected. May 3, 2019 at 10:39
  • @EricMORAND, there is already a follow-up question, see the linked question.
    – 4uk4
    May 3, 2019 at 11:21
  • MenuLinkContent's getEntity() method is public now (when Drupal 10.2.0 is released). See drupal.org/node/3361300
    – 4uk4
    Aug 17, 2023 at 9:46

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.