Skip to main content

Find the route name of the current page in Drupal 8

I was trying to generate a dynamic link to a Drupal Commerce product but couldn't figure out the correct route name. I finally got the route name with the following debugging code:

  1. $current_path = \Drupal::service('path.current')->getPath();
  2. $url_object = \Drupal::service('path.validator')->getUrlIfValid($current_path);
  3. $route_name = $url_object->getRouteName();
  4. $route_parameters = $url_object->getrouteParameters();

After inspecting those, variables, I determined that the route name for a Drupal Commerce entity is "entity.commerce_product.canonical" with a route parameter of "commerce_product" pointing to the entity ID. My full link generation code is:

  1. $link = Link::createFromRoute('View Details', 'entity.commerce_product.canonical', ['commerce_product' => $parent_entity->id()],['fragment' => 'variation-' . $entity->id()])->toRenderable();

Thanks to @bbu23's post that got me to find the answer:…