Creating a dynamic redirect page
Controllers for routes in Drupal can return request objects provided by the Symfony HttpFoundation
component instead of a render array. When a response object is returned, the render system is bypassed and the response object is handled directly.
In this recipe, we will create a route that redirects authenticated users to the homepage and anonymous users to the user login form.
How to do it…
- First, we need to create the
src/Controller
directory in the module’s directory. We will put our controller class in this directory, which gives our controller class theController
namespace:mkdir -p src/Controller
- Create a file named
RedirectController.php
in theController
directory. This will hold ourRedirectController
controller class. - Our
RedirectController
class will extend theControllerBase
base class provided by Drupal core:<?php
namespace Drupal\mymodule\Controller;
use Drupal\Core\Controller\ControllerBase;
class RedirectController...