Drupal 8 – Create a block plugin

This continues on from the previous post where we created a simple module. In this post we add a basic block, which is pretty easy as it turns out.

Create a new file at lib/Drupal/thrones/Plugin/Block/ThronesExampleBlock.php and add the following:

<?php

/**
 * @file
 * Contains \Drupal\thrones\Plugin\Block\ThronesExampleBlock.
 */

namespace Drupal\thrones\Plugin\Block;

use Drupal\block\BlockBase;
use Drupal\Component\Annotation\Plugin;
use Drupal\Core\Annotation\Translation;

/**
 * Provides a simple block.
 *
 * @Plugin(
 *   id = "thrones_example_block",
 *   admin_label = @Translation("Thrones Example Block"),
 *   module = "thrones"
 * )
 */
class ThronesExampleBlock extends BlockBase {

  /**
   * Implements \Drupal\block\BlockBase::blockBuild().
   */
  protected function blockBuild() {
    return array(
      '#children' => 'This is a block!',
    );
  }

}

Clear the cache and you should be able to add the block.

By Sam

Drupal developer from Perth, Western Australia. I love programming, gaming, the Internet, growing vegetables and hiking.

3 comments

  1. It seems that in D8 new block no longer appear in admin/structure/block automatically. They have to be “placed” do you know if there is a way to do that programmatically?

Leave a comment

Your email address will not be published. Required fields are marked *