How to load a form in a block in Drupal 8

You can use the following block code to load a form in a block in Drupal 8.

<?php

namespace Drupal\example_module\Plugin\Block;

use Drupal\Core\Block\BlockBase;

/**
 * Provides a 'ExmpleFormBlock' block.
 *
 * @Block(
 *  id = "ExampleFormBlock",
 *  admin_label = @Translation("Example Form Block"),
 * )
 */
class ExampleFormBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
    return \Drupal::formBuilder()->getForm('Drupal\example_module\Form\ExampleForm');
  }

}
 

Example Form is the class of form which has to be displayed in the block. You can also use core and contributed provided forms.

 

Tags