Views page redirect to current page with parameter in drupal 7, I use drupal_goto function for the redirection. I'm trying a few methods in d8, but couldn't make it work.

If I visited a certain page for example /views-page-example, I would like to redirect users to the same page, but with parameters. Once visited, the users should be redirected to /views-page-example?name=value. I'm using template_preprocess_page to trigger the redirection.

This is the current code I have so far:-

use Drupal\Core\Url;
use Symfony\Component\HttpFoundation\RedirectResponse;

function THEME_preprocess_page(&amp;$variables) {
  $current_path = \Drupal::service('path.current')-&gt;getPath();

  if ($current_path == '/views-page-example') {
    $path = "/views-page-example?name=value";
    $route_name = url::fromRoute($path);
    $response = new RedirectResponse($route_name-&gt;toString());
    $response-&gt;send();
  }
}
Don't send a response in custom code. Use an event subscriber to set the response, so that it can be returned by Drupal:

mymodule.services.yml:

services:
  mymodule.event_subscriber:
    class: Drupal\mymodule\EventSubscriber\MymoduleSubscriber
    tags:
      - {name: event_subscriber}


src/EventSubscriber/MymoduleSubscriber.php:

namespace Drupal\mymodule\EventSubscriber;

use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class MymoduleSubscriber implements EventSubscriberInterface {

  public function checkForRedirection(GetResponseEvent $event) {
    if ($event-&gt;getRequest()-&gt;query-&gt;get('redirect-me')) {
      $event-&gt;setResponse(new RedirectResponse('http://example.com/'));
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = ['checkForRedirection'];
    return $events;
  }

}


Source: https://www.drupal.org/node/2013014



Example to check the current path and that the query parameter is not present yet:

public function checkForRedirection(GetResponseEvent $event) {
  $request = $event-&gt;getRequest();
  if ($request-&gt;getPathInfo() == '/example' &amp;&amp; !$request-&gt;query-&gt;has('name')) {
    ...