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/Controllerdirectory in the module’s directory. We will put our controller class in this directory, which gives our controller class theControllernamespace:mkdir -p src/Controller
- Create a file named
RedirectController.phpin theControllerdirectory. This will hold ourRedirectControllercontroller class. - Our
RedirectControllerclass will extend theControllerBasebase class provided by Drupal core:<?php
namespace Drupal\mymodule\Controller;
use Drupal\Core\Controller\ControllerBase;
class RedirectController...