Programatically creating a custom block in Drupal 8

In drupal 8, It has become slightly difficult to create custom blocks in a programmatic method. One of the main reasons is that Drupal 8 is completely object oriented with complex coding structure. By keeping this in mind, we have written this Drupal tutorial which helps drupal developers to create a custom block in Drupal 8 programatically.

Here are the steps to create a custom block in Drupal 8:-

  1. Create your own module with standard info.yml file.

    In this case, we created a module called 'hello_glonius' and hello_glonius.info.yml with following code:-
     

    name: Hello Glonius
    description: An experimental module to create a custom block programmatically
    package: Glonius
    type: module
    version: 1.0
    core: 8.x

  2. Create customblock1.php file with the following code under /src/Plugin/Block.

    In Drupal 8, Block is considered as one of the plugin types. so it should be created under 'Plugin' folder. you can give any name instead customblock1.php but it must match your namespace in the code.
     

    /**
     * @file
     * Contains \Drupal\hello_glonius\Plugin\Block\customblock1.
     */
    namespace Drupal\hello_glonius\Plugin\Block;
    use Drupal\Core\Block\BlockBase;
    /**
     * Provides my custom block.
     *
     * @Block(
     *   id = "customblock1",
     *   admin_label = @Translation("Custom Block 1"),
     *   category = @Translation("Blocks")
     * )
     */

    class customblock1 extends BlockBase {
    /**
       * {@inheritdoc}
       */
      public function build() {
        return array('#markup' => 'Hi Glonius');
      }
    }

     

  3. Enable the module.

    Now if you go to '/admin/structure/block' and click 'Place block' near any region, our custom block would be displayed in the list. You can configure the settings and display the block in any region. If you add or modify block content in the code, make sure to clear cache to reflect the changes.

(Recommended: Drupal 8 Explained: Your Step-by-Step Guide to Drupal 8)

These are the important steps to create a basic block with some content. Hope it helps you to get some idea about drupal 8 custom block creation. Please contact us if you need any assistance.

Stay informed - subscribe to our newsletter.
The subscriber's email address.