0

Through the use of a Drupal 8 custom module for the purpose of providing the menu items/menu structure as a JSON resource, I have encountered a problem which I'm hoping someone will have an answer or lead for.

The output to the extent that it's currently functioning appears in JSON format, the structure following the same as the defacto menu system outputting title, weight, and whether the item is active.

    [
  {
    "title": "Vehicles",
    "url": {},
    "weight": "1",
    "active": true
  },
  {
    "title": "Automotive Parts",
    "url": {},
    "weight": "2",
    "active": true
  },

The URL is not displayed, even though in Drupal there are paths entered for the items. I have made several attempts at browsing the Drupal 8 documentation to search for answers about URL and menu classes. Currently, the relevant code responsible for the output is this one.

public function get($entity) {
$menu_name = $entity;
$menu_parameters = \Drupal::menuTree()->getCurrentRouteMenuTreeParameters($menu_name);
$tree = \Drupal::menuTree()->load($menu_name, $menu_parameters);
$result = array();

foreach ($tree as $element) {
  $link = $element->link;

  // if ($link->getUrlObject()->isExternal() == true) {
  //   $route = $link->getUrlObject();
  // }
  // else {
  //   // $route = $link->getUrlObject()->getInternalPath(); //this is breaking the module because apparently there are no "internal routes".
  // }
  dpm($link->getUrlObject());
  if ($link->isEnabled() == true) {
     array_push($result, array(
      'title' => $link->getTitle(),
      'url' => Url::fromUri($link->getUrlObject()->toUriString()),
      'weight' => $link->getWeight(),
      'active' => $link->isEnabled()
    )
  );
 }
}
return new JsonResponse($result);

}

How can I make the 'url' => part of the code output the path entered in Drupal for that menu item?

0

1 Answer 1

0

You'll want to use this kind of implementation based on the Alias Manager service.

<?php
$path_alias = \Drupal::service('path.alias_manager')->getAliasByPath($system_path, $langcode);
?>

Details and a further explanation can be found on D.O https://www.drupal.org/node/1853148

If you'd be willing, I'd also like to see the full code for that resource.

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.