Drupal 9: How to create a custom block

Por Fernando Katsukawa, 14 Janeiro, 2023

This should also work for Drupal 8 and Drupal 10 versions.

Custom blocks are piece of contents, code or logic that you can put inside pages in Drupal.

To create custom blocks, you will need to have a custom module.

Inside the custom module, you will need to create/use the following directory structure:

modules/custom/your_custom_module/src/Plugin/Block

Inside this directory structure, create a class, which you can name as MyCustomBlock.php

<?php

namespace Drupal\your_custom_module\Plugin\Block;

use Drupal\Core\Block\BlockBase;

/**
 * Provides a custom block.
 *
 * @Block(
 *   id = "my_custom_block",
 *   admin_label = @Translation("My custom block")
 * )
 */
class MyCustomBlock extends BlockBase {

  /**
   * {@inheritDoc}
   */
  public function build() {
    return [
      '#type' => 'markup',
      '#markup' => 'This is your custom block content.'
    ];
  }

}

This example MyCustomBlock class extends BlockBase, which will provide you some basic configuration and settings form.

Now you can enable your custom block using your website structure block admin page, like the others blocks provided by the Drupal core.

Sobre o Autor

Profile picture for user fkatsukawa

Fernando Katsukawa é desenvolvedor backend senior certificado, que já trabalha a 12 anos com o Drupal e contando...

Salvei seu valioso tempo? Use o copo abaixo para me comprar um cafezinho!
buy me a coffee - cup