Creating a Custom Block in Drupal: A Step-by-Step Guide
In this tutorial, we will walk through the process of creating a custom block in Drupal. This block will be displayed in the right-hand column of your site and will show the same message you see upon logging in.
Link to generating-a-block headingGenerating a Block
Although it's possible to create a block using the Drupal admin interface, for our purpose, we need to pull the message from the configuration settings created earlier. This requires defining the block in code, which is where the Drupal Console comes in handy. To generate the block code, use the following command:
drupal generate:plugin:blockWhen you run this command, you will be asked several questions. For the module name, type welcome. For the other questions, you can leave the default options, except for the question "Do you want to generate a form structure?"—here, choose 'no'. Selecting 'no' is important because we are pulling content from a previously saved configuration item, making a block configuration form unnecessary.
The Drupal Console will create a single file named DefaultBlock.php and a new folder called Block inside the Plugin folder. The full path will be:
/modules/custom/welcome/src/Plugin/Block/DefaultBlock.phpThis file contains the code for your custom block.
Link to adding-the-block-to-a-region headingAdding the Block to a Region
Now that the block is generated, the next step is to add it to a region on your site. To do this, follow these steps:
- Navigate to
Admin > Structure > Block layout. - Click on the "Place block" button next to the "Sidebar second" region.
- A "Place block" modal will pop up. Scroll down to find the "Default block for the Welcome module" and click on "Place block."
- After placing the block, click "Save block."
Your new block should now be listed under the "Sidebar second" region.
Link to viewing-the-block headingViewing the Block
Once you have saved the block, go back to your site's homepage. You should see the new block in the right sidebar with the default title and content. By default, the text displayed will be "Implement DefaultBlock," which is the placeholder text created by the Drupal Console.