Controller in Drupal 9
- Abhinesh Dhiman
- Mar 16, 2022
- 1 min read
Step 1: Name the Drupal 9 Module:
This is the first step to creating a module under the 'web/modules/custom 'folder. We will name that module as first_module.

Step 2: Create an info file:
Under the first_module folder, we will create an info.yml file starting from the machine name. In our case, it will be "first_module.info.yml".

Code:
name: "First Module" description: "Our First Module" type: module core_version_requirement: ^8.8.0 || ^9 || ^10
Step 4: Create a Controller:
Under the route "src/Controller" directory, create a file named "HelloController.php".

Code:
<?php namespace Drupal\first_module\Controller; use Drupal\Core\Controller\ControllerBase; class HelloController extends ControllerBase{ function sayHelloWorld(){ return[ "#type" => "markup", "#markup" => "Hello World", ]; } }
Step 5: Create a Routing.yml file:
Under the root of the module create a routing.yml file.

Code:
first_module.hello: path: '/Hello-world' defaults: _controller: 'Drupal\first_module\Controller\HelloController::sayHelloWorld' _title: 'Say Hi To The World' requirements: _permission: 'access content'
Step 3: Install:
Under the route "/admin/modules", we can find our first module and install that.

Step 4: Visit /Hello-world :

Comments