Drupal - What function/method can I use to redirect users to a different page?

This is the code that should be used in Drupal 8. See change Record for more info.

use Symfony\Component\HttpFoundation\RedirectResponse;

function my_goto($path) { 
  $response = new RedirectResponse($path);
  $response->send();
  return;
}

To build on Anu Mathew's response;

To add a status code, its just the second param in the RedirectResponse class;

use Symfony\Component\HttpFoundation\RedirectResponse;

function my_goto($path) { 
  $response = new RedirectResponse($path, 302);
  $response->send();
  return;
}

This can be achieved by leveraging built-in symphonies EventDispatcher Component. All you have to do is create a custom module. Add your services.yml file and provide appropriate service config.

services:
  mymodue.subscriber:
    class: Drupal\my_module\EventSubscriber
    tags:
      - { name: event_subscriber }

in Your modules src directory add the EventSubscriber.php class and describe you methods here.

<?php
namespace Drupal\my_module;

use Drupal\Core\Url;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;

class EventSubscriber implements EventSubscriberInterface {

  public function checkForCustomRedirect(RequestEvent $event) {    
    $request = $event->getRequest(); 
    $route_name = $request->attributes->get('_route');
    if($route_name === 'module.testPage') {
      $url = Url::fromRoute('<front>')->toString();
      $event->setResponse(new RedirectResponse($url));
    }
  }
      
  /**
  * {@inheritdoc}
  */
  public static function getSubscribedEvents() {
    return [KernelEvents::REQUEST => [['checkForCustomRedirect']]];
  }
}

Tags:

8

Redirection