Generating A Module with Drupal Console
Share with Others
Drupal Console is a command line tool for Drupal (similar to Drush) that has built in code generation tools. This makes it easy to generate boilerplate code for a custom Drupal 8 module. In this episode, we discuss how to use Drupal Console to generate an example module with an administrative settings form.
The first step is to install Drupal Console. You can do that with composer using:
composer require drupal/console
This will install Drupal console in your project in the ./vendor/bin/ directory. This means you can run Drupal console using:
Note, in my examples I am using Lando for my local development environment. I have it set up to allow me to run Drupal console commands on my site by running lando drupal. You can decide to install Drupal Console globally and add it to your path. Depending on the development environment your setup might be slightly different.
You can get a list of all the Drupal console commands by running Drupal Console command with no command argument:
To generate a boilerplate module with Drupal console run:
Fill out the questions asked by Drupal console. Make sure to enter a module name and description. The rest of the options can be left at their defaults (in the example below I also added a Package name):
At the end of the questions Drupal console will ask you if it should proceed with creating the module for you. Hit enter to default this to yes.
You can now see that this has generated a boilerplate module for you. You can now look at this generated code and even install this module on your Drupal site.
We will now use Drupal console to generate and administrative form. This can be started by running the following command:
The first step is to enter your module name. This should autocomplete as you type. After that you need to add a Form Classname. In the example below, I used SettingsForm. The next four questions can be left at their defaults:
When you tell Drupal console you want to generate a form structure, it will provide you a list of form elements and walk you through a form builder process. In this example, I just created a textfield called My Textfield. Go ahead and generate some form fields.
When you are finished, just leave the New field type question blank and press the Enter key. It will then ask you some questions regarding the path and menu links.
After this it will generate the code for you.
Now all you need to do is enable your module, find the link in your admin menu, and you now have an Admin settings form!
There is so much more you can do with this. As the module currently sits, it doesn’t do much, however, it provides a solid base for you to start developing your own custom module. Spend some time looking through the generated code and feel free to make modifications to the custom module you built.