Add a Form to the Block Configuration

Last updated on
22 March 2017

Now let us say that we want to add the ability for the site builder to enter a piece of configuration for each instance of our custom block. Always keep in mind that all site building configuration in Drupal 8 can be exported from the development site and imported to the production site (known as Configuration Management). You, as a module builder can also provide a default configuration to auto-fill the form when the site builder instantiates a new block.

In your existing HelloBlock class from the previous page, add these "use" statements following the one that is already there:

use Drupal\Core\Block\BlockPluginInterface;
use Drupal\Core\Form\FormStateInterface;

Update the class declaration to include this new "implements BlockPluginInterface" statement:

class HelloBlock extends BlockBase implements BlockPluginInterface {

Then add the following method to the class. A similar, complete file is here, but note that the form name and config names are not the same as this tutorial.

This code will only add the form, processing of the form and saving the results will follow in the next pages.

  /**
   * {@inheritdoc}
   */
  public function blockForm($form, FormStateInterface $form_state) {
    $form = parent::blockForm($form, $form_state);

    $config = $this->getConfiguration();

    $form['hello_block_name'] = array(
      '#type' => 'textfield',
      '#title' => $this->t('Who'),
      '#description' => $this->t('Who do you want to say hello to?'),
      '#default_value' => isset($config['hello_block_name']) ? $config['hello_block_name'] : '',
    );

    return $form;
  }

In this example, the form is first defined by the reference to its parent class through the following code statement $form = parent::blockForm($form, $form_state );. Next, we are adding a new field to the form. This process is called polymorphism and is one of the important advantages of using Object-Oriented Programming(OOP) techniques.

To view the form, go to your previously added instance in admin->structure->Block Layout and click on Configure for the (Hello Wold) block.