Drupal 8: How to create a custom block programatically
Blog

Drupal 8: How to create a custom block programatically

In Drupal 8 Blocks are made up of two separate API. Block Plugin API, is a reusable API and Block Entity API, use for block placement and visibility control.

Before we begin with custom Block module development. We assume that you’ve better understanding of Plugin API & Annotation-based plugins.

Creating a custom block require following steps:

  1. Create a block plugin using Annotations

  2. Extend the Drupal\Core\Block\BlockBase class.

In Drupal 8, We need to keep the keep our custom,  contributed module in root directory

modules/custom

module/contrib

Step 1:  An essential part of a Drupal 8 module, theme, or install profile is the .info.yml file (aka, "info yaml file") to store metadata about the project.

In Drupal 8, .info file changes to .info.yml. Old .info files have been converted to YAML.

Added name, description, core, package, dependencies, type (The type key, which is new in Drupal 8, is required and indicates the type of extension, e.g. module, theme or profile.

 

Step 2:  We should follow the PSR-4 standard code for custom block(s) & that has to be placed into article/src/Plugin/Block/ and named based on the class it contains. If we're going to define the class ArticleBlock this file would be article/src/Plugin/Block/ArticleBlock.php

s33

 

Create a file ArticleBlock.php under modules/custom/article/src/Plugin/Block folder structure

Annotation contains just the id and label:

  1. The 'id' property in the annotation defines the unique, machine readable ID of your block.

  2. The 'admin_label' annotation defines the human readable name of the block that will be used when displaying your block in the admin interface.

  3. The 'Category' defines which section belongs to under block listing page.


     

The ArticleBlock extends BlockBase class. This class provides generic block configuration form, block settings and handling of user defined block visibility settings.

 

Where are we displaying markup in our block ?

Save the file and enable the module. To enable a block visit /admin/structure/block and click on “place block” under one of the region. i’m selecting “Sidebar Second” for my visibility or search for your block “Article block” click on “place block” and configure it.

s36

 

s37

So, we have done with configuration. it’s time to visit our page. as we set the block to  page.

s38

 

Git Source code: https://github.com/xaiwant/drupal8-block

Download the Drupal Guide
Enter your email address to receive the guide.
get in touch