Ronnie February 2016

Getting a menu delivered via REST

I am trying to get a menu via REST and I've created a new module and rest resource plugin that allows for GET on /entity/restmenu/{menu_name}.

I can successfully return this example json using this function when I hit the URL.

public function get(EntityInterface $entity) {
  $result = array();
  for ($i = 0; $i < 10; $i++) {
    $temp = array(
      'title' => 'Test ' . $i,
      'href' => '#/' . $i
    );
    array_push($result, $temp);
  }
  return new ResourceResponse(json_encode($result));
}

I cannot figure out how to load the menu based on $entity. If I hit my URL (http://dang.dev:8888/entity/restmenu/main?_format=hal_json) $entity's value is 'main' which is the machine name of the main menu.

I've tried using Drupal menu tree, but I am not having luck, and debugging this thing with only JSON responses is quite difficult.

How do I get menu item titles and paths based on the menu machine name?

EDIT

Ok, sort of figured it out.

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

  foreach (end($renderable) as $key => $val) {
    $temp = array(
      'menu_item' => $val,
      'route' => $key
    );
    array_push($result, $temp);
  }
  return new ResourceResponse(json_encode($result));
}

Right now that will output:

[
  {
    "menu_item":{
      "is_expanded":false,
      "is_collapsed":false,
      "in_active_trail":false,
      "attributes":"",
      "title":"Home",
      "url":{

      },
      "below":[

      ],
      "original_link":{

           

Answers


Ronnie February 2016

This was the correct answer:

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;
    array_push($result, array(
        'title' => $link->getTitle(),
        'url' => $link->getUrlObject()->getInternalPath(),
        'weight' => $link->getWeight()
      )
    );
  }
  return new ResourceResponse(json_encode($result));
}

Post Status

Asked in February 2016
Viewed 2,061 times
Voted 9
Answered 1 times

Search




Leave an answer