Create a custom block

Last updated on
18 January 2017

Blocks in Drupal 8 are instances of the block plugin.
The Drupal block manager scans your modules for any classes that contain a @Block Annotation.

The example snippet below makes use of the @Block annotation along with the properties "id" and "admin_label" to define a custom block.

Create the file src/Plugin/Block/HelloBlock.php within the module skeleton created earlier and add the code below. You will, of course, need to rebuild the cache.

<?php

namespace Drupal\hello_world\Plugin\Block;

use Drupal\Core\Block\BlockBase;

/**
 * Provides a 'Hello' Block
 *
 * @Block(
 *   id = "hello_block",
 *   admin_label = @Translation("Hello block"),
 * )
 */
class HelloBlock extends BlockBase {
  /**
   * {@inheritdoc}
   */
  public function build() {
    return array(
      '#markup' => $this->t('Hello, World!'),
    );
  }
}

To add 'Hello block' you can go to Structure -> Block Layout (admin/structure/block) and click on 'Place Block' button associated with each available region.

Clicking on 'Place Block' button for any given region a "Place Block" dialogue pop-up will appear, with a listing of all available blocks. To quickly find your block, simply use 'Filter by block name' option or use mouse-scroll to locate 'Hello block'. This way you can add any number of instances of the custom block anywhere on your site.

Note: The class name and the file name must be the same ( class HelloBlock and /src/Plugin/Block/HelloBlock.php). If the class name is different, the block will appear in the list of available blocks, however you will not be able to add it.

Troubleshooting: Be sure to double check all paths and filenames. Your .php must be in the correctly labelled directory (/src/Plugin/Block/), otherwise it won't be discovered by Drupal.