7

I have a custom entity named Application that has an Entity Reference field named Product.

When I am on an Apllication page and click on a Product to see it, I would like to know that I come from the Application page and know its ID.

This would allow me to display information from the Application page on the Product page.

But how to do it ?

4
  • The information will need to be displayed only when one comes from application page or anyone who visits product will see the associated application info ?
    – GiorgosK
    Mar 10, 2018 at 15:30
  • Only when someone comes from the application page to the product page. Mar 11, 2018 at 19:59
  • 1
    There might be a new module which can do that: drupal.org/project/referer_to_entity_reference
    – andir
    Dec 21, 2018 at 3:14
  • Did my answer help you? maybe you can consider checking it as accepted. Aug 26, 2022 at 1:35

2 Answers 2

10

This method works for me:

use Symfony\Component\HttpFoundation\Request;
use Drupal\Core\Url;
// Getting the referer.
$request = \Drupal::request();
$referer = $request->headers->get('referer');
// Getting the base url.
$base_url = Request::createFromGlobals()->getSchemeAndHttpHost();
// Getting the alias or the relative path.
$alias = substr($referer, strlen($base_url));
// Getting the node.
$params = Url::fromUri("internal:" . $alias)->getRouteParameters();
$entity_type = key($params);
$node = \Drupal::entityTypeManager()->getStorage($entity_type)->load($params[$entity_type]);

// To use dpm you need the devel module.
dpm($node->id());
dpm($node->title->value);
0
$previousUrl = \Drupal::request()->server->get('HTTP_REFERER');
$fake_request = Request::create($previousUrl);
$url_object = \Drupal::service('path.validator')->getUrlIfValid($fake_request->getRequestUri());
$route_name = $url_object->getRouteName();
$url = Url::fromRoute($route_name, $url_object->getRouteParameters());
$previousPath = $url->getInternalPath();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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