Skip to main content

November 6, 2014

Video and Blog Tutorial: Programmatically Creating a Block in Drupal 8

Thought by Matt Korostoff, Team Lead

hook_block_info and hook_block_view are gone in Drupal 8. What's more the whole paradigm of creating blocks through the hook system is replaced with the Plugin API . In fact, the D8 road map called for eliminating all info hooks, though I'm unsure of the status of that initiative at the moment.

This is part 1 in our series on the Drupal 8 plugin system. Today I will show how to create a block from scratch, entirely with custom code. In our next post, we will demonstrate an even easier, automated strategy using the Console module.

  1. Create and enable a custom module.

    We're not actually going to use the .module file here, but I find it's convenient to have an empty module file around for testing experimental code. Checkout my first Drupal 8 module on Github for a really simple boilerplate.
  2. Create a new plugin.

    A "plugin" is just a new way of creating reusable elements in Drupal. Blocks are now created with plugins. modules/yourmodule/src/Plugin/Block/YourBlockName.php

    Here I am creating a custom next/previous block.
  3. Declare a new class in your plugin.

    A few things to note here: first of all the class name (in this case, YourBlockName on line 17) must match the filename (YourBlockName.php). Your namespace must be the name of your module followed by \Plugin\Block (line 6). The only method that you absolutely must implement is the build() method. The comment/docblock above the class definition is also mandatory. Unlike most docblocks that you've probably worked with in the past, this docblock has a functional impact&em;that's one big adjustment in D8, functional docblocks. The "id" in particular will be used when this block is exported to code later.
  4. Clear your cache.

    You can do this with drush with the command drush cr.
  5. Add your block to the page.

  6. Export your configuration to code (optional).

    If you prefer to keep your block configuration in code you may do so with `drush config-export`. Here's how the block looks once its been exported:

    Note that the "id" on line 7 is the one you declared in your docblock earlier.
  7. Rejoice!