Complete Guide to Creating Custom Drupal Modules
If you are a developer or want to extend the functionality of Drupal, creating custom modules is the way to go. Custom modules allow you to add new features, integrations, and more, tailored specifically to your project’s needs. In this comprehensive guide, we will walk through the entire process of creating a custom Drupal module.
1. What Is a Drupal Module?
A module in Drupal is a collection of files (usually PHP) that extend the core functionality of the system. Modules can provide new features, alter existing functionality, or integrate with third-party services. Modules in Drupal can be either contributed (from Drupal’s community) or custom-built to meet unique requirements.
2. Creating the Module Directory
First, you need to create a directory for your module. This directory will contain all the necessary files, including the module code and configuration.
- Navigate to the module directory:
- Go to your Drupal installation directory and then navigate to
modules/custom/
. - If the
custom
directory doesn’t exist, create it.
- Go to your Drupal installation directory and then navigate to
- Create your module folder:
- Inside
modules/custom/
, create a directory for your custom module. - For example, let’s create a module called
hello_world
. The path would look like this:modules/custom/hello_world
.
- Inside
3. Creating the .info.yml
File
Every Drupal module needs an .info.yml
file. This file tells Drupal important information about your module such as its name, type, description, dependencies, and more.
- Create a file named
hello_world.info.yml
inside thehello_world
directory. - Add the following code:
name: 'Hello World'
type: module
description: 'A custom Drupal module that displays Hello World.'
core_version_requirement: ^8 || ^9
package: Custom
dependencies:
- drupal:core
Explanation of fields:
name
: The name of your module.type
: Type of the item (module in this case).description
: A short explanation of what your module does.core_version_requirement
: Specifies the Drupal core versions compatible with the module.package
: Defines the category where the module will appear in the admin interface.dependencies
: Lists other modules that your module depends on.
4. Creating the .module
File
The .module
file is where the core logic of your module will go. You can define functions, hooks, and more in this file.
- Create a file named
hello_world.module
inside thehello_world
directory. - Add a simple hook to display “Hello World”:
/**
* Implements hook_help().
*/
function hello_world_help($route_name) {
switch ($route_name) {
case 'help.page.hello_world':
print t('This module displays a simple Hello World message.');
}
}
/**
* Implements hook_menu().
*/
function hello_world_menu() {
$items = array();
$items['hello'] = array(
'title' => 'Hello World',
'page callback' => 'hello_world_page',
'page arguments' => array(),
'access callback' => 'TRUE',
'type' => MENU_CALLBACK,
);
return $items;
}
/**
* Page callback function for Hello World.
*/
function hello_world_page() {
return 'Hello World!';
}
5. Enabling the Module
Once you’ve created the necessary files, it’s time to enable the module.
- Clear the Drupal cache to ensure it picks up your new module.
- Enable the module using Drush (Drupal’s command-line tool) or via the UI:
- If you are using Drush, run:
drush en hello_world
- Alternatively, go to the Extend page in the Drupal admin interface and enable the
Hello World
module.
- If you are using Drush, run:
6. Test the Module
To test your new module:
- Navigate to
http://yoursite.com/hello
. - You should see the message
Hello World!
displayed on the page.
7. Adding Routes with routing.yml
To make your module more dynamic and provide more advanced features, you can create routes with the routing.yml
file. This allows your module to define URL paths and map them to controller methods.
- Create a
hello_world.routing.yml
file. - Add the following code to define a route:
hello_world.content:
path: '/hello-world'
defaults:
_controller: '\Drupal\hello_world\Controller\HelloWorldController::helloWorld'
_title: 'Hello World'
requirements:
_permission: 'access content'
- Create the Controller class (
src/Controller/HelloWorldController.php
):
namespace Drupal\hello_world\Controller;
use Drupal\Core\Controller\ControllerBase;
/**
* Class HelloWorldController.
*/
class HelloWorldController extends ControllerBase {
/**
* Displays the Hello World page.
*/
public function helloWorld() {
return [
'#markup' => $this->t('Hello World!'),
];
}
}
8. Adding a Configuration Form
To make your module more dynamic, you can add configuration forms so users can change settings via the admin interface.
- Create a
src/Form/SettingsForm.php
file. - Add a simple configuration form:
namespace Drupal\hello_world\Form;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
/**
* Configure settings for Hello World.
*/
class SettingsForm extends ConfigFormBase {
/**
* {@inheritdoc}
*/
protected function getEditableConfigNames() {
return ['hello_world.settings'];
}
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'hello_world_settings';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$config = $this->config('hello_world.settings');
$form['message'] = [
'#type' => 'textfield',
'#title' => $this->t('Hello Message'),
'#default_value' => $config->get('message'),
'#description' => $this->t('The message to display on the page.'),
];
return parent::buildForm($form, $form_state);
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$this->config('hello_world.settings')
->set('message', $form_state->getValue('message'))
->save();
parent::submitForm($form, $form_state);
}
}
- Add the route for this form in
hello_world.routing.yml
:
hello_world.settings:
path: '/admin/config/hello-world'
defaults:
_form: '\Drupal\hello_world\Form\SettingsForm'
_title: 'Hello World Settings'
requirements:
_permission: 'administer site configuration'
Now, you can access the form through /admin/config/hello-world
to modify the “Hello World” message.
9. Conclusion
Creating custom Drupal modules is a powerful way to extend and personalize the Drupal experience. From adding simple “Hello World” features to complex functionalities, the flexibility of Drupal allows you to build exactly what you need.
By following these steps, you now have a basic understanding of how to create a custom module, integrate forms, and handle routing. As you get more comfortable, you can explore more advanced topics like events, services, and Drupal’s Entity API.