Create a custom block

Last updated on
16 June 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"),
 *   category = @Translation("Hello World"),
 * )
 */
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.

Troubleshooting 

  • 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.

  • 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.

  • If your block fails to place in a region with no error on screen or in watchdog, check the PHP / Apache error logs.

Note: Using Twig templates with custom blocks

  1. Add a _theme hook in your .module file. Don't name the theming function like 'block__...' - this will not pass any variables down to the twig templates. Instead, you might use the module name as prefix.
  2. Use '#theme' in the render array in the build method and pass the variables on the same level as the '#theme' - '#varname'.