0

Linking through menu link tree elements I'm getting a series of url objects and paths. What I'd like to do is turn those url objects or paths into entities. I want access to the actual entities that they refer to. Here's my code so far:

$menu_tree = \Drupal::menuTree();
$menu_parameters = $menu_tree->getCurrentRouteMenuTreeParameters($menu_id);
$menu_tree_elements = $menu_tree->load($menu_id, $menu_parameters);
foreach ($menu_tree_elements as $menu_tree_element) {
  $menu_tree_link = $menu_tree_element->link;
  $url_object = $menu_tree_link->getUrlObject();
  $path = $url_object->toString();
  $url_params = \Drupal\Core\Url::fromUserInput($path)->
    getRouteParameters();
  var_dump($url_params);
}

I was thinking that I could possibly get the entity from the url parameters but I get the error

External URLs do not have internal route parameters.

Which makes sense to me because I have menu links that refer to just general Page entities not nodes. Like '/about'.

However I'm able to get to the paths just fine. Is there a way that I can load an entity since I have a url object that has a path directly leading to it?

UPDATE: I tried using

$params = \Drupal\Core\Url::fromUserInput('/about')->
  getRouteParameters();
var_dump($params);

But all that did was return an empty array.

I received the same result when using

$params = \Drupal\Core\Url::fromUri("internal:/about")->
  getRouteParameters();
0

I managed to come up with a solution by using the storage manager to load the entity using the path to load it.

$page = \Drupal::entityTypeManager()
  ->getStorage('page')
  ->loadByProperties(array(
      'path' => $path
  ));

I'm assuming you can use the same method for nodes.

  • @Cyclonecode Not necessarily disagreeing but can you explain why was your edit to my code a better formatted answer? Is it convention to have those methods formatted like a staircase like that? I've never seen drupal code formatted in that matter. – Matt Mar 16 '18 at 17:32
  • 2
    @Cyclonecode I'm reediting your edit to follow the conventions of the actual drupal core code. See the source code of the UserAuth class as an example api.drupal.org/api/drupal/… – Matt Mar 16 '18 at 17:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.