How to Create a Custom Block Programmatically in Drupal 8?

 1. Create a module

    To create a custom block, it is necessary to create a “.info.yml” file in modules/custom directory. Here a custom directory does not exist. You will need to create it. Create a directory named “custom” under the module directory. And under “modules/custom” create a directory called “block_welcome”. This directory name will be the name of the module created.
Inside this folder that you just created, create a “<module name>.info.yml” file. Here it will be block_welcome.info.yml as the module name is block_welcome. Within this file, enter the following contents:

name: 'Welcome block module'
type: module
description: 'sample module'
core: 8.x
package: 'Custom'
dependencies:
  -drupal:block


After creating the folder and file with the above content, go to the dashboard and enable the module you just created. The name of the module here is Welcome block module.


2. Create a Drupal Block Class

Now to define the logic for the block, we must define the Drupal block class. The php class of the block is placed under modules/custom/block_welcome/src/Plugin/Block directory. Create this folder structure and create a class named WelcomeBlock.php under the Block directory.
This file should contain:
<?php   
namespace Drupal\block_welcome\Plugin\WelcomeBlock;
 
/**
 * Provides a block with welcome text.
 *
 * @Block(
 *   id = "welcome_block",
 *   admin_label = @Translation("Welcome Block"),
 * )
 */
class WelcomeBlock extends BlockBase {
}

The WelcomeBlock extends Blockbase class which will provide generic block configuration form, block settings, and handling of user defined block visibility settings.


<?php   
namespace Drupal\block_welcome\Plugin\WelcomeBlock;
 
/**
 * Provides a block with welcome text.
 *
 * @Block(
 *   id = "welcome_block",
 *   admin_label = @Translation("Welcome Block"),
 * )
 */
class WelcomeBlock extends BlockBase {

 /**
   * {@inheritdoc}
   */
  public function build() {
    return [
    '#type' => 'markup',
    '#markup' => 'welcome to drupal 8 block'
    ]
  }
}


Here we are displaying a markup in the block.


3. Enable the Block to display the content

  •     After saving the file to enable the block, go to admin > Structure > Block layout.
  •     Click on Place block under the region the block should be displayed. 
  •     After clicking on Place block, search for the custom block you just created.

    Click on Place block for the block you want to display. The configuration window opens where you can set the configuration as per requirement and save.




The Drupal 8 custom block created is now visible in the region where the block is placed.

Comments