3 Ways to Programmatically Create a Block in Drupal 8

3 Ways to Programmatically Create a Block in Drupal 8

Step into the block-shaped world of Drupal 8! You'll surely feel like playing with some sort of “building blocks set” for grown-ups as you'll be picking and adding blocks of content to different regions on your website, as you'll switch them and mix and match them to your liking. And yet, before you even get to do all these block “maneuvers”, you definitely need to learn how to programmatically create a block in Drupal 8, right? It's a multiple-choice type of task, so let me “expose” to you the 3 ways available to you for creating a brand new block, so that you can pick whichever suits your “style” as a Drupal developer!

Blocks, blocks, blocks! Any Drupal 8 website is built on a blocks-made infrastructure! 

It's these very “boxes” of content themselves, that you get to “sprinkle” anywhere on your website, that actually put together a Drupal 8 site!

Now as a Drupal site builder and, most of all, as one already familiarized with Drupal 7, you'll surely “fall for” Drupal 8's more than intuitive interface. From creating, to editing, to deleting some of your blocks, each one of these processes is surprisingly intuitive!

And now let's go back to the very purpose of this blog post: revealing and detailing to you 3 equally tempting ways to programmatically create a block in Drupal 8! You should know, from the start, that yes: implementing a new block has changed since Drupal 7! 

You'll see that:

  • everything is far more organized, with code for each and every block nicely structured in its own class (no more “throwing” everything block-related in the “.module” file, like we used to do in the “good” old days when Drupal 7 ruled over the Drupal kingdom)
  • creating a new block in Drupal 8 is surprisingly similar to creating any kind of entity; you just need to go for the right service and pay attention to correctly filling in all those fields

And now, let's go on with the promised “trio”: 3 ways for creating a new block in Drupal 8!

But First: What's Changed in The Drupal Block UI Since Drupal 7?

There are 2 differences worth your full attention:

  1. the block layout page will no longer list all the blocks, but only those corresponding to certain regions on your Drupal 8 site (sidebar first, content etc.)
  2. you get to assign one block to multiple regions (since blocks are entities in Drupal 8); and this is a tremendous improvement!

Moreover, as already mentioned, navigating in your Drupal 8 Bock UI is so very intuitive!

For instance, here's how you can assign a block to a certain region on your site:

  1. navigate to URL /admin/structure/block 
  2. hit the “Place Block” button
  3. next just go through all the available blocks displayed to you in the overlay popping up

3 Ways to Programmatically Create a Block in Drupal 8: assigning a block to a region

And now, let's proceed with those 3 methods to choose from when you want to programmatically create a block in Drupal 8:

1. Create a Block Right in The Drupal 8 UI

For yes: you can add a brand new custom block right from your block layout interface! Since blocks have their own dedicated page in Drupal 8 (and it's similar to any content page), where you get all the entities of type “block” listed (it uses views to display them all)!

So “How it's done?” you say? 

Step 1: you navigate to your Custom Block Library from your toolbar menu: Structure -> Block Layout -> Custom Block Library

Step 2: click “Add custom block” and simply choose the type of block you wish to add 

3 Ways to Programmatically Create a Block in Drupal 8: creating a new custom block

2. Create a New Block in Code 

If you prefer “getting your hands dirty” in code, then go ahead!

Creating new blocks in Drupal 8 via code, by leveraging Drupal 8's APIs, is nothing but an intuitive, two-step process:

2.1 Create a simple module 

Step 1: first create a new custom folder under “/modules/custom”, naming it ““my_block_example”

Step 2: there, in that newly created folder, create your “.info.yml” file: my_block_example.info.yml

            - as you well know, in Drupal 8 the “.info.yml” file replaces the “.info” file, while the old “.info” files have been transferred to YAML. It's precisely in this “info yaml” file that metadata about your website gets stored

             - it's here, in this “info.yml” file, that you get to add your block's name, its description, its dependencies, the package type (the required type key is the one indicating your block's extension type, e.g.: profile, module or theme)

name: Article Block

description: Defines a custom block.

core: 8.x

package: Custom


- block

type: module

Step 3: enable your module

Note: Keep in mind, though, that we can no longer talk about a “.module” file in Drupal 8 (like it was the case with the block creation process in Drupal 7)

2.2. Define a Block Class 

Now you need to define the class that will incorporate the logic of your new block.

Step 1: apply the PSR-4 standards for custom blocks and place your PHP class under /modules/custom/my_block_example/src/Plugin/Block

Step 2: next create the MyBlock.php right underneath

Step 3: finally, your block's path should look like this: my_block_example/src/Plugin/Block/MyBlock.php

Your newly created file will incorporate two sections:

  • Annotation: it contains meta data relevant for your Block (you get to use the annotations plugins for handling your block's subject, its “admin_label” inserted in the comment block, your block's “id”, as well)
  • MyBlock: a class including 4 different methods:
    build(), blockAccess(), BlockForm() and BlockSubmit()
    More about each one's functionality you'll find in this post on how to programmatically create a block in Drupal 8!

And next go ahead and create your new block!

All there's left for you to do is to get it assigned to the right region on your website! 

3. Programmatically Create a Block in Drupal 8 Using The Drupal Console

Have you already had the chance to harness the Drupal Console's superpower?

Then how about doing it again? This time for creating a new custom block in... the blink of an eye!

Practically the console empowers you to generate the boilerplate code of your future block! 

Here's how it's done:

  1. open up your terminal
  2. access your Drupal site's root folder
  3. enter the following command into that folder: drupal generate:plugin:block
  4. pick the module that you'll want your custom block to be created under 
  5. just answer all the popping up questions there 

And that's it! 

How about you? Have you, by any chance, applied other method, different from these 3 mentioned here, to programmatically create a block in Drupal 8? Do share!

Or simply leave your feedback, in the comments section below, on any of these 3 ways, if you're already tried any of them!