Create a custom block programatically in drupal 8

Creating a block in drupal 8 is easy. Just follow the steps and you will be ready with a block

Go to your drupal 8 files and there is a module folder

In module folder create a folder named your module name. I am going to make a new folder named mahi and inside your module name you have to follow php PSR4 convention. So your file structure will be like modulename/src/Plugin/Block/filename.php.

The module file contains 2 important files one is and another is modulename.module

So it will look like this


Now open your .php file and add the following lines of code


namespace Drupal\mahi\Plugin\Block;
use Drupal\Core\Block\BlockBase;
* Provides a ‘mahi’ block.
* @Block(
*     id = “mahi_block”,
*     admin_label = @Translation(“Mahi Block”),
*     category = @Translation(“Custom article block example”)
* )
class MahiBlock extends BlockBase {
public function build() {
return array(
‘#type’ => ‘markup’,
‘#markup’ => ‘This block list the article.’,

Now open your .info.yml and write the following code

name: Mahi Block
description: A simple module for Block.
core: 8.x
package: Custom
– node
– block
type: module

Dont add anything in .module file

Now go to drupal-8 site and extend that module

Now go to block configuration and place your block at your choice

Refresh the site and your block will be displayed



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s