How to create a custom block in Drupal 8?

Member

by larissa , in category: PHP Frameworks , 9 months ago

How to create a custom block in Drupal 8?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by darrion.kuhn , 3 months ago

@larissa 

To create a custom block in Drupal 8, you can use one of the following methods:

  1. Use the Drupal Console to generate a block plugin:
1
drupal generate:plugin:block


  1. Create a block plugin manually:
  • Create a folder for your custom module, if it doesn't already exist.
  • Create a src folder in your custom module folder.
  • Create a Plugin folder in the src folder.
  • Create a Block folder in the Plugin folder.
  • Create a PHP file for your custom block in the Block folder. The file name should follow the pattern {BLOCK_NAME}Block.php.
  • Define your custom block class in the PHP file. The class should extend the BlockBase class and implement the BlockPluginInterface interface.
  • Annotate the block class with @Block annotation.
  • Implement the build() method, which should return the content (formatted as a render array) that you want to display in the block.


Here is an example of a custom block class:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<?php

namespace DrupalmymodulePluginBlock;

use DrupalCoreBlockBlockBase;
use DrupalCoreBlockBlockPluginInterface;
use DrupalCoreFormFormStateInterface;

/**
 * Provides a 'MyCustomBlock' block.
 *
 * @Block(
 *   id = "mycustom_block",
 *   admin_label = @Translation("My custom block"),
 *   category = @Translation("Custom"),
 * )
 */
class MyCustomBlock extends BlockBase implements BlockPluginInterface {

  /**
   * {@inheritdoc}
   */
  public function build() {
    $build = [];
    $build['mycustom_block']['#markup'] = 'Hello World!';

    return $build;
  }

}


  1. Use the Drupal user interface to create a custom block:
  • Go to the "Structure" menu and click on the "Block layout" link.
  • Click on the "Place block" button for the region where you want to add the custom block.
  • In the "Add custom block" section, enter a name and a description for your custom block.
  • In the "Block body" field, enter the content that you want to display in the block.
  • Click on the "Save block" button.


I hope this helps! Let me know if you have any further questions.