1

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.

  • 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 '17 at 15:19
3
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;
    }
  }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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