How to Develop a Custom Drupal Module

6m
Eduard Grigalashvili
Technical Writer

Please note that Drupal 8 reached its end of life on November 17, 2021. However, Drupal custom module development in Drupal 8 and Drupal 10 is quite similar, so this information can help you regardless of which version of the CMS you're using. Still, you should consider migrating to the latest Drupal version if you're on Drupal 8 for security reasons. Learn more about the benefits of Drupal 10 and how to migrate to Drupal 10 in our article "Drupal 10 is Here: New Features and Improvements, How to Upgrade". In case you need a reliable Drupal development company for your project, feel free to reach out to us.

The existing Drupal 8 functionality is very extensive. Like all the previous versions of Drupal, it gives developers a lot of opportunities to implement their plans. However, there are a number of cases where the built-in toolkit is not enough. And in this case, modules come to the rescue. These are special extensions of the current Drupal features that help to maximally customize the solution being created on the basis of this platform.

Generally speaking, you can find three types of modules for Drupal 8:

  • core;

  • contributed;

  • custom.

The first type of modules comes directly from the platform itself, and they were created by the Drupal developers. The second type is modules co-written by the Drupal community and released under the GPL license. Finally, the third type of modules (those that will be discussed below), are very narrowly specialized solutions that developers make on the spot - that is, when all previous modules have turned out to be either useless for solving a specific business problem, or less effective than required.

Below we will discuss how to develop a custom Drupal module.

Before We Begin

Before proceeding directly to the Drupal 8 module development, let’s discuss the specifics of the process. This information will be extremely useful for those who have previously dealt only with Drupal 7.

As you know, Drupal 7 has a procedural coding style. In the case of Drupal 8, developers have to switch to object-oriented programming. This allows them to abstract themselves from implementation details, to protect certain data from unauthorized access, and, finally, to scale the existing code without too much risk of causing errors that would be difficult to solve.

To make all the tangible differences clearer, we suggest analyzing them using the following table:

Platform version

Drupal 7

Drupal 8

Programming style

procedural

object oriented

File type used to initialize variables

.info

.yml

Ability to use plugins

no, all functions must be written manually

yes

Ability to use PHP annotations

no

yes

The need to route between a URL and a callback function

available with the help of hook_menu()

no, all this is automatically implemented through the use of classes

Creating Our First Custom Module for Drupal 8

So, after analyzing the differences between the Drupal 7 and Drupal 8 versions, we suggest finally proceeding to our small tutorial on custom Drupal modules development. Below, you will find a comprehensive guide on how to create a custom module for your Drupal site.

Here you will learn how to create a module that would associate the controller with URLs and return custom blocks.

1. Selecting a name for the Drupal custom module and creating a folder for it

Before you create custom module in Drupal, you will have to come up with a unique name for your specific solution, as well as the name of the machine that will be used within the module itself.

Ready? Great, now it's time to make a folder in which to place your creation. According to the traditions of Drupal 8 development, this folder is placed inside the “sites/all” directory and it has the standard name “modules”.

After you have created the modules category for all your future custom modules, it is time to create a category for our particular case. Suppose that our module is called My Module, and the machine is called my_module, respectively. In this case, the folder we need to create should be named my_module too.

2. Creating the files

Now you will need to build a file with the extension .info.yaml (in our case it will look like my_module.info.yml) and a file with the extension .module (in our case it will be my_module.module).

3. Creating a directory to place the files

The next step in our tutorial will be the creation of a src subfolder to accommodate plug-ins, templates and other files of our project. This will automatically load the class controllers of your future module.

4. Creating the base controller

In order to create a base controller, you will need to create another directory called Controller in the src folder. In this directory, you need to create the MyController.php file. To begin, write something into this file (for example, a primitive program with the output line “This is my first module”) to observe how it works:


<?php

namespace Drupalmy_moduleController;

use DrupalCoreControllerControllerBase;

class MyController extends ControllerBase {

public function content() {

  return array( '#type' => 'markup', '#markup' => t('This is my first module'), );

}

}

5. Creating a route file

Now we need to get our controller to start doing something really useful. To do this, we will now create it (in our case it will be named my_module.routing.yml) and connect it to the route from the URL:


first_module.content:

path: '/first'

defaults:

  _controller: 'Drupalmy_moduleControllerMyController::content'

  _title: 'This is my first module'

requirements:

  _permission: 'access content'

6. Launching the module

So, we are launching our module. In order for the user to receive content, your module must receive URL information. The most convenient way to implement all of this is to create a new file with the extension .menu.yml and place it in the root directory. Inside the file, you will need to write the following code:


my_module.admin:

title: 'First module settings'

description: 'A basic module to return a string'

parent: system.admin_config_development

route_name: my_module.content

weight: 100

7. Clearing the cache

Now clear the cache (this is done so that you can see your new menu item).

8. Creating a custom block

For these purposes, you will need to create a new plugin. To do this, in the src folder, create a new directory called Plugin, and inside it another directory called Block. Inside the Block directory, you will need to create a new file (in our case it will be called MyPluginBlock.php). Here, you either have to manually specify the classes and namespaces to use, or they will be pulled up automatically, in case you use some IDE during development. Put the following code there:


<?php

namespace Drupalmy_modulePluginBlock;

use DrupalCoreBlockBlockBase;

class MyPluginBlock extends BlockBase {

}

9. Adding a new method

The next step is to organize the inheritance of the child classes and add a new method inside the HelloBlock class:


class HelloBlock extends BlockBase {

public function build() {

return array(

    '#markup' => $this->t('This is my first module'),

 );

}

}

10. Clearing the cache again

After clearing the cache, go to the administrative panel. Here we will need to add our block to the sidebar. To do this, you will need to click Place block and save this option with the needed settings. Now scroll to the bottom of the administration page and click Save blocks.

Voila! Your module is ready! Now you can try to change something to suit your own taste. As you can see, Drupal module development is not that difficult.

Creating a custom module in Drupal 8 and Drupal 10: Differences and Similarities

As noted in the introduction, the development of Drupal custom modules in Drupal 8 and Drupal 10 is quite similar, with some key differences due to updates and improvements in the latest version of the CMS. Let's review key similarities and differences:

Similarities:

  • File structure. The basic structure of custom modules remains the same. You still need to create a .info.yml file and a .module file. Your module directory will typically contain subdirectories for code (like src for PHP classes), templates, and configuration.
  • Routing and controllers. Defining routes and controllers uses the same principles. You still define routes in a .routing.yml file and create controllers that extend the base Controller class.
  • Configuration management. Configuration management with .yml files is consistent across both versions. Custom modules will still define configuration in the same way using .schema.yml and .install files.
  • Services and dependency injection. Both versions use the Symfony Dependency Injection component. You will register services in a module.services.yml file and inject dependencies into your classes using the service container.

Differences:

  • PHP and Symfony versions. Drupal 10 uses newer versions of PHP (8.1) and Symfony (6.2), which changes the way how you write your PHP code and interact with the Symfony components. Some deprecated features from older version of Symfony used in Drupal 8 are removed in newer versions.
  • Modern JavaScript. Drupal 10 supports more modern JavaScript practices and libraries compared to Drupal 8. If your module includes front-end components, you'll need to ensure compatibility with the latest JavaScript standards.
  • Deprecated code removal. Drupal 10 has removed several deprecated APIs that were still present in Drupal 8. This includes changes to various hooks, service definitions, and utility functions. You will need to ensure that your code does not rely on any deprecated APIs that were removed in Drupal 10.
  • New features. Drupal 10 introduces new features and improvements that you can leverage in your custom module in Drupal This includes enhancements in the Layout Builder, Media Library, and better support for modern development practices.

Conclusion

In our Drupal 8 module development tutorial, we have created a custom module for the Drupal 8 platform that returns a string, forms a route, and creates a new block on the user’s side. We hope that this will help you to create new, more complex modules that will help adapt your website to your needs.

If you would rather not develop the module yourself, and in general would like to avoid wasting your time and jangling your nerves on customizing your site, then you can hire a Drupal developer. Our best developers from the company AnyForSoft will take care of any task, no matter how difficult, in the shortest possible time. Drop us the line using the form below, even if you just want to ask: “How much does it cost to develop a Drupal module?” We will be glad to start a new cooperation!

Want to work with us?