Main menu

You are here

Creating a custom block in Drupal 8

Submitted by sharique on Mon, 06/09/2014 - 19:51

Block is a very basic building block of any site. Blocks in drupal 8 are very different from what we are using in d7. In D8 blocks are plugins (like ctool content type plugin) and also entity. One more major improvement from site builder is that now you can have more than one instance of a block on same page, all instances can have different configuration, which was nightmare in d7. In d7 to achieve this you have to use either use panels or delta + context modules. Even in this way you can’t have different configuration for each instance. By creating mini panels you can have different configuration for each mini panel, which make page heavy and it will be slower to load. Now you can do this easily without using any contrib module.

Creating custom block using code is much easier in D8 as compared to D7. All that you have to do is create a class using BlockBase as base in “my_module/src/Plugin/Block” and implement at build function, which is for building block. If you look closely at the path, you will realize that you’re creating new Block type plugin.
The code of for creating is as follows

The build method is the heart of the block, it returns the markup of the block in array format.Method buildForm is for configuration form of the block. Here I’ve defined only one text field, value entered will be displayed on the block. I am doing this to show that each block instance will separate configuration. Method getConfiguration is used to retrieve the saved configuration of the block. Did you noticed that there is no form_submit, you don’t need to a submit method to save the configuration, if you are doing some processing than you need one. Method for submit is blockSubmit.