Creating our first module in Drupal 8

By: Rolando Payan Mosqueda

Drupal 8 is just around the corner and it's going to be a revolution, not an evolution like Drupal 7 was compared to Drupal 6, as it has a completely different architecture and coding methodology. I'm convinced that these major changes were necessary to professionalize and modernize the CMS. I think the shift to object-orientation will be of interest to developers and will improve the quality of the software in general.

I am very grateful to the Drupal core developers for their bravery and work on all of this! And to help you get familiar with this new version I will show you how to create a module in Drupal 8.

WARNING : Please note that because Drupal 8 is still in development at the time of writing, some parts of the code may not work for you, so please let us know if this happens, so we can fix it immediately.

Well let's start:

Naming and positioning your module in Drupal 8

The first thing we must do is create a folder with the machine name of our module. This is used in the names of various files and functions in your module, and is used by the Drupal core to refer to your module. Remember this name:

  • It must start with a letter.
  • It may contain lowercase letters and underscores.
  • Must be unique. Your module cannot have the same name as another module, theme, or installation profile that you will use on your site.

Important Note : Be sure not to use capital letters in your module name or Drupal will not recognize your  hook implementations .

We then select " hello " for its name.

Previous versions of Drupal had core modules in /modules however in Drupal 8, this folder is now for modules you develop yourself. All files including core modules and libraries are now in the /core directory. In Drupal 8, you can still use the Drupal 7/6 best practice of putting your custom modules and those downloaded from Drupal.org (contrib) in /sites/all/modules but putting it in the /modules directory has the same effect.

Giving information to drupal 8 about your module.

Inside this folder we create a hello.info.yml file which is similar to the .info in previous versions of Drupal:

The first three lines are mainly used in the administration user interface by allowing users to install or uninstall the module. The name and description keys are required and indicate the text displayed on the module management page, and the package key allows you to group all modules that define this key; Drupal 8 core, for example, uses the core package to group all of its modules, just as you can use the custom package to group all of your custom modules together making them easier to locate.

The type key, which is new in Drupal 8, is required and indicates the type of extension, for example, module, theme, or profile.

The core key is also mandatory and specifies which version of Drupal your module is compatible with.

And that's it, just one file. Now you can go to the Extend page, find the module you just created, and enable it.

 

So far it doesn't have any functionality, so we're going to make it show us a message when visiting a specific page.

Defining our route

As you may have  read , several Symfony components have been added to Drupal 8, including  Routing , so the way of defining a route in Drupal 8 changes, now we must create a file following the following pattern: {your_module_name}. routing.yml in our case hello.routing.yml:

Important note : To indent or indent the beginning of each line in these YAML files, it is prohibited to use tabs, for this we must use spaces, otherwise our code would cause problems.

hello.hello:

Esta línea es el nombre de nuestra ruta. Generalmente se construye de la siguiente manera: {nombre_de_su_módulo}.{acción} Esta puede ser utilizada en otras partes de código, por ejemplo para generar una URL basado en una ruta.

path: '/hello'

Aquí se define la URL de la ruta, o sea, que en nuestro navegador, podremos verla apuntando a www.example.com/hello

Debajo de defaults tenemos:

_controller: '\Drupal\hello\Controller\HelloController::hello'

El cual hace referencia al método a ejecutar al acceder a la URL anterior. Lleva la forma \Drupal\{nombre_del_módulo}\{carpeta_del_controlador}\{nombre_de_la_clase}::{método}

_title: 'Is anyone here?'

Título que tendrá la página.

Debajo de requirements tenemos:

_permission: 'access content'

Permisos necesarios para acceder a esta página. En este caso cualquier usuario podrá acceder a ella.

Usted pude consultar esta página de documentación para más opciones a incluir en este archivo de enrutamiento.

Creando nuestro primer controlador

Ahora debemos crear el controlador para esta ruta, este retornará el mensaje “Hello from Drupal 8”.

Dentro de nuestra carpeta del módulo crearemos una subcarpeta llamada src.

Esto significa "source", y es parte del estándar PSR-4 así que nuestra clase controladora será cargada automáticamente.

Dentro de la carpeta "src" creamos otra carpeta llamada Controller.

Otra vez, es parte del estándar. Dentro de la carpeta "Controller", creamos un archivo llamado HelloController.php, quedando con la siguiente estructura:

 

Ahora dentro el archivo HelloController.php escribiremos lo siguiente:

Simplemente es todo lo que debemos hacer para para mostrar un texto en una página. En el inicio del archivo especificamos el namespace y abajo declaramos la clase.

Dentro de la clase HelloController, solo tenemos el método hello que retorna un render array parecido a como se hacía en Drupal 7, nada más.

Todo que tenemos que hace el instalar el módulo o si lo habíamos hecho antes, limpiar cache ("drush cr" ó ir a Configuration->Performance->Clear all caches) e ir a nuestra página que acabamos de crear: http://www.example.com/hello:

 

Adicionando a nuestro menú

En Drupal 7 cuando implementamos hook_menu, podíamos también registrar un acceso directo en los menús. Esto también, ya no es gestionado por el hook_menu, para acometer esto debemos hacerlo mediante un archivo YAML.

Veremos entonces cómo mostrar un enlace en nuestro menú de Herramientas.

Creamos un archivo hello.links.menu.yml en la raíz de nuestro módulo:

 

Con el siguiente contenido:

Como podrá observar en la primera línea tenemos nuestro nombre de la ruta.

Then we will see the title, the description (when we hover over the link), the menu name (where it will be positioned), and the name of the route we want to appear in that menu. If you notice, it is the same route assigned in our hello.routing.yml file. If we omit the menu_name key, Drupal will automatically position our link in the Tools menu. We have only put it here to explain the key.

Next we clear cache and it should show in our Tools menu:

 

Well that's all, we have created a fairly basic module in Drupal 8, in the next installments we will go a little deeper, so stay tuned.