Step 1: Create the Module Folder
Navigate to the modules/custom directory in your Drupal installation and create a new folder for your module. Name it my_module.
Step 2: Create the Info.yml File
Create a file named my_module.info.yml inside your module folder and add the following content:
name: 'My Custom Module'
type: module
description: 'A custom module for Drupal.'
core_version_requirement: ^9 || ^10
package: Custom
Step 3: Create the Module File
Create a file named my_module.module. This file can be empty or contain hooks.
Step 4: Create the Routing File
To create a custom page, add my_module.routing.yml with the following content:
my_module.custom_page:
path: '/custom-page'
defaults:
_controller: 'Drupal\my_module\Controller\MyModuleController::customPage'
_title: 'Custom Page'
requirements:
_permission: 'access content'
Step 5: Create the Controller
Inside the module folder, create a directory src/Controller and add a file named MyModuleController.php with this content:
<?php
namespace Drupal\my_module\Controller;
use Drupal\Core\Controller\ControllerBase;
class MyModuleController extends ControllerBase {
public function customPage() {
return [
'#markup' => 'Hello, this is a custom page!',
];
}
}
Step 6: Clear Cache and Enable the Module
Run the following command to enable the module:
drush en my_module -y
Clear the cache to apply changes:
drush cr
Conclusion
Now, visit /custom-page on your Drupal site to see your custom module in action!
0 Comments