3

I need to conditionally pass contextual filter values to a view based on the current route and am attempting to do so in hook_views_pre_view. This is the result of using AJAX via views_infinite_scroll and losing the contextual filters that I initially pass in programmatically.

On the initial request, the following works great for getting the current route in hook_views_pre_view:

$current_route_match = \Drupal::getContainer()->get('current_route_match');
$current_route_match->getRouteName();

However, when I hit the 'Load more' button supplied by views_infinite_scroll, the route name of the current route match is 'views.ajax'. While I understand that this is technically the request's route, I need to know the original route, or from where the request was made.

After digging around, I noticed that $_SERVER['HTTP_REFERER'] had the right path, but the documentation says:

Not all user agents will set this, and some provide the ability to modify HTTP_REFERER as a feature. In short, it cannot really be trusted.

1
  • False alarm. While accessing the "original route" in the midst of an AJAX request would be helpful, I discovered that my problem was actually a misunderstanding of Views. I have two contextual filters for a view and was passing in false as the first in an effort to not filter by any value. For some reason this worked on the initial page request but ended up evaluating to null on the subsequent AJAX requests, being ignored completely. This bug caused me to think that contextual filters - applied programmatically - did not persist through multiple requests. Luckily I was wrong :)
    – cole
    Mar 20, 2017 at 15:19

1 Answer 1

6
use Symfony\Component\HttpFoundation\Request;

if (\Drupal::routeMatch()->getRouteName() == 'views.ajax') {
    $previousUrl = \Drupal::request()->server->get('HTTP_REFERER');
    $fake_request = Request::create($previousUrl);
    $url_object = \Drupal::service('path.validator')->getUrlIfValid($fake_request->getRequestUri());
    if ($url_object) {
      $route_name = $url_object->getRouteName();
      // Do something with $route_name;
    }
  }
1
  • $previousUrl can be null, e.g. when is the first page visited by the user. With PHP 8.1+ it causes the warming Deprecated function: parse_url(): Passing null to parameter #1 ($url) of type string is deprecated. It may be better to add a check on the existence of $previousUrl
    – Giuseppe
    Jul 12 at 8:37

Your Answer

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

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