“This is the real secret of life -- to be completely engaged with what you are doing in the here and now. And instead of calling it work, realize it is play.” ― Alan Watts

Drupal 8 - Get the referrer page's routename

September 16, 2019

I needed to create a Drupal action link that would update some custom config entities. But I wanted the user to remain on the current page after clicking this action link, essentially I needed to redirect back to this referral page from the controller that would update the entities. 

Explicitly defining a route to return to would not work since the referral page was not always known.

I couldn't find a way to get the route name of the previous page, there didn't seem to be a method for this. So I had to come up with a solution myself. Here is the controller I created.

<?php

namespace Drupal\my_module\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\my_module\UpdateConfigEntities;
use Symfony\Component\HttpFoundation\Request;

class RefreshEntitiesLists extends ControllerBase {

  public function process() {
    // I call the method that updates my config entities
    UpdateConfigEntities::process();
    
    // Get the request data
    $request = Request::createFromGlobals();
    // Parse the referral URL to retain just the path
    $uri = parse_url($request->headers->get('referer'), PHP_URL_PATH);
    // Get the URL object
    $urlObject = \Drupal::service('path.validator')->getUrlIfValid($uri);
    // Get the route name
    $route = $urlObject->getRouteName();
    // Return to referral page using routename
    return $this->redirect($route);
  }

}

If you know a better way let me know!