Entity view (Content)

Drupal 8: Creating a configurable block

By stran
Sep. 30, 2016

Drupal 8 blocks are implemented as plugins.  Plugins are basically "small pieces of functionality that are swappable" (https://www.drupal.org/developing/api/8/plugins). 

We'll create a simple Hello block that takes in name and simply prints it out.

First we'll create a module called Hello to store this block.  To do that, we simply create a .info.yml file like so: /modules/custom/hello/hello.info.yml

name: Hello
type: module
description: Hello module
core: 8.x

Next we'll create the block. Create the following file /modules/custom/hello/src/Plugin/Block/HelloBlock.php

<?php

namespace Drupal\hello\Plugin\Block;

use Drupal\Core\Block\BlockBase;

/**
 * Provides a 'HelloBlock' block.
 *
 * @Block(
 *  id = "hello_block",
 *  admin_label = @Translation("Hello block"),
 * )
 */
class HelloBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
    $build = [];
    $build['hello_block']['#markup'] = 'Hello World.';

    return $build;
  }

}

A few things to note here. 

* @Block(
*  id = "hello_block",
*  admin_label = @Translation("Hello block"),
* )

is required because that is how Drupal will discover your block.  It's equivalent to hook_block_info in Drupal  7.

We're also extending the BlockBase class.  This provides us with useful functionalities for configuring our block.

Right now, our block simply prints out the text 'Hello World'. We want to make this block be configurable, so let's override BlockBase's blockForm() and blockSubmit() methods.

/**
 * {@inheritdoc}
 */
public function blockForm($form, FormStateInterface $form_state) {
  $form['name'] = array(
    '#type' => 'textfield',
    '#title' => $this->t('Name'),
    '#description' => $this->t('Your name'),
    '#default_value' => isset($this->configuration['name']) ? $this->configuration['name'] : 'John Doe',
    '#maxlength' => 64,
    '#size' => 64,
    '#weight' => '0',
  );

  return $form;
}

/**
 * {@inheritdoc}
 */
public function blockSubmit($form, FormStateInterface $form_state) {
  $this->configuration['name'] = $form_state->getValue('name');
}

This allows us to configure the block and enter in our custom name. To display our name, we simply modify the build() to 

/**
 * {@inheritdoc}
 */
public function build() {
  $build = [];
  $build['hello_block']['#markup'] = '<p>' . $this->configuration['name'] . '</p>';

  return $build;
}

Now simply enable our Hello module and use the block administration interface to place our block in any region.

Post Tags: