Specbee: Programmatically Creating a Block in Drupal 9 – A Brief Tutorial

Programmatically Creating a Block in Drupal 9 – A Brief Tutorial Suresh Prabhu 07 Dec, 2021

Blocks are an integral part of any Drupal website. They are chunks of content that can be placed in various regions and can be easily moved around the web page. Blocks can contain simple text, forms, or some complex logic. The Block module is a core module since Drupal 8 and simply needs to be enabled to get it to work. Sometimes, installing other core or contributed modules can automatically enable them too.

Although these blocks can be modified to suit the layout, complete flexibility and customization can only be achieved with custom blocks. You can create a custom block programmatically or via the Drupal Interface. Here, we will be creating a block programmatically and enabling it through the admin interface.

Drupal 8 has now reached EOL. Now is the time to migrate to Drupal 9. However, if you’re still trying your hands out at creating a custom module in Drupal 8, these steps will work for a Drupal 8 setup too. 

Custom block Drupal 9

How to Create a Custom Block in Drupal 9?

Let us get started with creating a custom block in Drupal 9 in a few simple steps:

1. Create a module

To create a custom block, it is necessary to create a “.info.yml” file in modules/custom directory. Here a custom directory does not exist. You will need to create it. Create a directory named “custom” under the module directory. And under “modules/custom” create a directory called “block_example”. This directory name will be the name of the module created.
Inside this folder that you just created, create a “.info.yml” file. Here it will be block_example.info.yml as the module name is block_example. Within this file, enter the following contents:
 

block_example.info.yml
block_example.info.yml

After creating the folder and file with the above content, go to the dashboard and enable the module you just created. The name of the module here is Block Example.

example block

 

2. Create a Drupal Block Class

Now to define the logic for the block, we must define the Drupal block class. We need to follow PSR-4 standard code for custom blocks. The php class of the block is placed under modules/custom/block_example/src/Plugin/Block directory. Create this folder structure and create a class named ExampleBlock.php under the Block directory.
This file should contain:

  • Annotation metadata – This will help to identify the Block created. To know more about Annotation check Annotations-based plugins.
  • Annotation contains:
      The “id” which is a unique, machine readable ID for the custom block created.
      The “admin_label” defines the human readable name of the custom block which is displayed in the admin interface.          
custom block
Custom block

The ExampleBlock extends Blockbase class which will provide generic block configuration form, block settings, and handling of user defined block visibility settings.

custom block
Custom block

Here we are displaying a markup in the block.

3. Enable the Block to display the content

  • After saving the file to enable the block, go to admin > Structure > Block layout.
  • Click on Place block under the region the block should be displayed. Here the block is placed in ‘Sidebar second’.
  • After clicking on Place block, search for the custom block you just created.
     

Place block

 

  • Click on Place block for the block you want to display. The configuration window opens where you can set the configuration as per requirement.

save custom block

Here the block is displayed for every user’s front page. After the configuration is changed as per the requirement, click on Save block and come back to the site.

Drupal 9 Custom Block
Drupal 9 Custom Block

The Drupal 9 custom block created is now visible in the region where the block is placed.

4.Methods used in the class created for custom blocks

  • build() : This method will render a render-able array. In this example a simple markup is returned. Even the complex contents like forms and views can also be returned.
  • blockAccess() :  This method defines a custom user access logic.

methods of custom block

                       • The AccessResult class is called here. 
                       • The method allowedIfHasPermission() checks if the current user has thepermission to view this content or not.
 

  • blockForm() : This method allows to define a block configuration form. 

custom block in drupal 8 module

 

  • blockSubmit() : This method is used to save the configuration defined in the previous method blockForm(). custom block in drupal 8

     

  • blockValidate() : This method validates the configuration form of the block. custom block in drupal 8

     

 

 

This article was republished from its original source.
Call Us: 1(800)730-2416

Pixeldust is a 20-year-old web development agency specializing in Drupal and WordPress and working with clients all over the country. With our best in class capabilities, we work with small businesses and fortune 500 companies alike. Give us a call at 1(800)730-2416 and let’s talk about your project.

FREE Drupal SEO Audit

Test your site below to see which issues need to be fixed. We will fix them and optimize your Drupal site 100% for Google and Bing. (Allow 30-60 seconds to gather data.)

Powered by

Specbee: Programmatically Creating a Block in Drupal 9 – A Brief Tutorial

On-Site Drupal SEO Master Setup

We make sure your site is 100% optimized (and stays that way) for the best SEO results.

With Pixeldust On-site (or On-page) SEO we make changes to your site’s structure and performance to make it easier for search engines to see and understand your site’s content. Search engines use algorithms to rank sites by degrees of relevance. Our on-site optimization ensures your site is configured to provide information in a way that meets Google and Bing standards for optimal indexing.

This service includes:

  • Pathauto install and configuration for SEO-friendly URLs.
  • Meta Tags install and configuration with dynamic tokens for meta titles and descriptions for all content types.
  • Install and fix all issues on the SEO checklist module.
  • Install and configure XML sitemap module and submit sitemaps.
  • Install and configure Google Analytics Module.
  • Install and configure Yoast.
  • Install and configure the Advanced Aggregation module to improve performance by minifying and merging CSS and JS.
  • Install and configure Schema.org Metatag.
  • Configure robots.txt.
  • Google Search Console setup snd configuration.
  • Find & Fix H1 tags.
  • Find and fix duplicate/missing meta descriptions.
  • Find and fix duplicate title tags.
  • Improve title, meta tags, and site descriptions.
  • Optimize images for better search engine optimization. Automate where possible.
  • Find and fix the missing alt and title tag for all images. Automate where possible.
  • The project takes 1 week to complete.