Reader small image

You're reading from  Drupal 10 Development Cookbook - Third Edition

Product typeBook
Published inFeb 2023
PublisherPackt
ISBN-139781803234960
Edition3rd Edition
Tools
Concepts
Right arrow
Authors (2):
Matt Glaman
Matt Glaman
author image
Matt Glaman

Matt Glaman is an open source developer who has been working with Drupal since 2013. Since then, he has contributed to Drupal core and over 60 community projects. He is also a speaker at multiple Drupal community events, including DrupalCon. Matt is currently a principal software engineer at Acquia and was previously a product lead at Centarro, helping maintain Drupal Commerce.
Read more about Matt Glaman

Kevin Quillen
Kevin Quillen
author image
Kevin Quillen

Kevin Quillen has been working with Drupal since 2006. He's contributed several community modules, and built websites using Drupal for brands such as Dogfish Head Craft Brewery, the National Bureau of Economics, Harvard University, MTV, Yale University, Verizon, the Museum of Science, and countless others. You can find him engaged and helping community members on Slack, Drupal StackExchange, or sharing his thoughts on his personal blog. Kevin is also an Acquia Triple Certified Drupal Expert, an Acquia Certified Site Studio Site Builder, and an Acquia Certified Cloud Platform Pro. He is currently a principal developer and Drupal practice lead at Velir.
Read more about Kevin Quillen

View More author details
Right arrow

Creating Custom Pages

In this chapter, we will make custom pages with controllers. A controller is a class that contains a method used to build a page when Drupal is accessed at a specific path. Creating custom pages allows you to extend Drupal beyond just the content pages. This chapter will cover the process of creating custom pages, receiving dynamic values from paths, and serving JSON or file download responses.

In this chapter, we will learn about the following recipes:

  • Defining a controller to provide a custom page
  • Using route parameters
  • Creating a dynamic redirect page
  • Creating a JSON response
  • Serving files for download

Technical requirements

This chapter requires an existing custom module installed on your Drupal site. This custom module will contain the controllers created throughout this recipe. Chapter 4, Extending Drupal with Custom Code, covers how to create a custom module. You can find the full code used in this chapter on GitHub: https://github.com/PacktPublishing/Drupal-10-Development-Cookbook/tree/main/chp05

Defining a controller to provide a custom page

Whenever an HTTP request is made to a Drupal site, the path for the URL is routed to a controller. Controllers are responsible for returning the response for a path that has been defined as a route. Generally, these controllers return render arrays for Drupal’s render system to convert into HTML.

In this recipe, we will define a controller that returns a render array to display a message on the page.

How to do it…

  1. 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 the Controller namespace:
    mkdir -p src/Controller
  2. Create a file named HelloWorldController.php in the controller directory. This will hold our HelloWorldController controller class.
  3. Our HelloWorldController class will extend the ControllerBase base class provided by Drupal core:
    <?php
    namespace Drupal\mymodule\Controller...

Using route parameters

In the previous recipe, we defined a route and controller that responded to the /hello-world path. A route can add variables to the path, called route parameters, so that the controller can handle different URLs.

In this recipe, we will create a route that takes a user ID as a route parameter to display information about that user.

Getting started

This recipe uses the route created in the Defining a controller recipe to provide a custom page.

How to do it…

  1. First, remove the src/Routing/RouteSubscriber.php file and mymodule.services.yml from the previous section and clear the Drupal cache, so it does not interfere with what we are about to do.
  2. Next, edit routing.yml so that we can add a route parameter of user to the path:
      path: /hello-world/{user}

Route parameters are wrapped with an opening bracket ({) and a closing bracket (}).

  1. Next, we will update the requirements key to specify that the user parameter...

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…

  1. 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 the Controller namespace:
    mkdir -p src/Controller
  2. Create a file named RedirectController.php in the Controller directory. This will hold our RedirectController controller class.
  3. Our RedirectController class will extend the ControllerBase base class provided by Drupal core:
    <?php
    namespace Drupal\mymodule\Controller;
    use Drupal\Core\Controller\ControllerBase;
    class RedirectController...

Creating a JSON response

Routes can also return JavaScript Object Notation (JSON) responses. A JSON response is often used for building API routes since it is an interchange format that is supported by all programming languages. This allows exposing data to be consumed by a third-party consumer.

In this recipe, we will create a route that returns a JSON response containing information about the Drupal site.

How to do it…

  1. 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 the Controller namespace:
    mkdir -p src/Controller
  2. Create a file named SiteInfoController.php in the Controller directory. This will hold our SiteInfoController controller class.
  3. Our SiteInfoController class will extend the ControllerBase base class provided by Drupal core:
    <?php
    namespace Drupal\mymodule\Controller;
    use Drupal\Core\Controller\ControllerBase;
    use Symfony...

Serving files for download

Routes can be used to serve file downloads with the BinaryFileResponse response object. Using the BinaryFileResponse to serve a file for download allows you to keep the original file’s URL private or to send dynamic content as a file download.

In this recipe, we will create a route that provides a download for a PDF.

Getting started

This recipe uses a PDF file that is located in the same directory as the module. You can use any other available file type, such as a text file. A test PDF can be found on the World Wide Web Consortium website at https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf.

How to do it…

  1. 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 the Controller namespace:
    mkdir -p src/Controller
  2. Create a file named DownloadController.php in the Controller directory. This...
lock icon
The rest of the chapter is locked
You have been reading a chapter from
Drupal 10 Development Cookbook - Third Edition
Published in: Feb 2023Publisher: PacktISBN-13: 9781803234960
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Authors (2)

author image
Matt Glaman

Matt Glaman is an open source developer who has been working with Drupal since 2013. Since then, he has contributed to Drupal core and over 60 community projects. He is also a speaker at multiple Drupal community events, including DrupalCon. Matt is currently a principal software engineer at Acquia and was previously a product lead at Centarro, helping maintain Drupal Commerce.
Read more about Matt Glaman

author image
Kevin Quillen

Kevin Quillen has been working with Drupal since 2006. He's contributed several community modules, and built websites using Drupal for brands such as Dogfish Head Craft Brewery, the National Bureau of Economics, Harvard University, MTV, Yale University, Verizon, the Museum of Science, and countless others. You can find him engaged and helping community members on Slack, Drupal StackExchange, or sharing his thoughts on his personal blog. Kevin is also an Acquia Triple Certified Drupal Expert, an Acquia Certified Site Studio Site Builder, and an Acquia Certified Cloud Platform Pro. He is currently a principal developer and Drupal practice lead at Velir.
Read more about Kevin Quillen