Find the route name of the current page in Drupal 8

Profile picture for user Phil Frilling
By Phil Frilling, 17 October, 2018

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:



$current_path = \Drupal::service('path.current')->getPath();
$url_object = \Drupal::service('path.validator')->getUrlIfValid($current_path);
$route_name = $url_object->getRouteName();
$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:

$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: https://www.drupal.org/forum/support/module-development-and-code-questi…