Drupal 8 – How to create a custom Block / Plugin

custom-block

Let’s create a Custom Block in Drupal 8 using Block Plugin API, it is similar to creating a custom module.

i)  First thing first, we need to create a folder and an info file. So, go to your-drupal-folder/modules/custom/ and create a folder “my_custom_block” and create a file under it as “my_custom_block.info.yml“, now put the below code in the info file.

name: My Custom Block
description: A Custom Block Plugin
type: module
core: 8.x
version: 1.0
package: custom
dependencies:
  - block

 

ii)  The second step is to create a PHP Class (CustomBlock.php – **you can name anything you want) and it should go under this path your-drupal-folder/modules/custom/my_custom_block/src/Plugin/Block/CustomBlock.php

In this class, you should have a @Block Annotation with properties “id“, “admin_label” and optionally “category“. Also, it should extend the BlockBase from Drupal core.

Let’s create the class:

<?php

/**
 * @file
 * Contains \Drupal\my_custom_block\Plugin\Block
 */

namespace Drupal\my_custom_block\Plugin\Block;

use Drupal\Core\Block\BlockBase;


/**
 * below section is important
 * 
 * @Block(
 *  id = "my_custom_block",
 *  admin_label = @Translation("My Custom Block"),
 *  category = @Translation("Custom")
 * ) 
 */
 
class CustomBlock extends BlockBase{
  public function build(){
    return [
      '#type' => 'markup',
      '#markup' => $this->t("Here is my custom block content")
    ];
  }
}

?>

 

Just go through above code and it’s very important to have the @Block Annotation otherwise your block won’t show up in the Block section.

Your folder structure would look like this now:

my_custom_block

iii) Now we have all our files in place, go to /admin/modules and enable the module.

my_custom_block_extend

iv) After enabling the module, go to /admin/structure/block and click the “Place block” button to place our custom block in any of the regions. I am going placing it under “Sidebar second

 

place-block

Click the “Place block” and then “Save Block” to save it.

save-block

That’s all we have placed our block. Now open your home page and see how the block appeared.

block-appear

I hope this would have helped you to learn how to create a Block in Drupal 8. Please Subscribe my blog for the new updates.

I am attaching the module file in this post, Please download/clone it from the below link (Github).

download

Leave a Reply

Theme: Overlay by Kaira
Agurchand