Step-by-Step Guide to Creating a Controller in Drupal 8/9/10

28 / Apr / 2023 by Rajveer Singh 0 comments
  1. Create a custom module: If you haven’t already done so, create a custom module in Drupal 10. You can refer to the previous question for a step-by-step guide on creating a custom module.
  2. Define the routing file: In the module folder, create a new file with the extension “.routing.yml”. This file defines your module’s page’s URL path and corresponding controller. For example, if you want to create a controller for the path “/ttn-hello-world”, your routing file would look like this:
custom_module.ttn_hello_world:
path: '/ttn-hello-world'
defaults:
_controller: '\Drupal\custom_module\Controller\TTNHelloWorldController::content'
_title: 'TTN Hello, World!'
requirements:
_permission: 'access content'

In this example, the "custom_module.ttn_hello_world" route maps to the "TTNHelloWorldController::content" controller, which we'll define in the next step. The "_title" parameter sets the page title, and the "_permission" parameter restricts access to users with the "access content" permission.
  1. Create the controller class: In the module folder, create a new file with the extension “.php” in the “src/Controller” directory. This file defines the controller class for your page. For example, if you want to create a controller for the path “/ttn-hello-world”, your controller class would look like this:
<?php

namespace Drupal\custom_module\Controller;

use Drupal\Core\Controller\ControllerBase;

class TTNHelloWorldController extends ControllerBase {

/**
* Returns the page content.
*/
public function content() {
$output = [
'#markup' => $this->t('TTN Hello, World!'),
];
return $output;
}

}

Now clear cache and access page : /ttn-hello-world

FOUND THIS USEFUL? SHARE IT

Leave a Reply

Your email address will not be published. Required fields are marked *