Inserting a form into a block in Drupal?

Viewed 25684

Is there any command or method that I can use to insert the contents of a form (e.g. the user registration form) into a block?

3 Answers

Drupal 8+ solution

Create the form. Then, to create the block use something like this:

<?php

namespace Drupal\my_module\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\my_module\Form\MyForm;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Provides the My Block block.
 *
 * @Block(
 *   id = "my_block",
 *   admin_label = @Translation("My Block")
 * )
 */
class MyBlock extends BlockBase implements ContainerFactoryPluginInterface {

  /**
   * The form builder.
   *
   * @var \Drupal\Core\Form\FormBuilder
   */
  protected $formBuilder;

  /**
   * Constructs a new MyBlock object.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
   *   Our service container.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, ContainerInterface $container) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->formBuilder = $container->get('form_builder');
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container
    );
  }

  /**
   * {@inheritdoc}
   */
  public function build() {
    $form = $this->formBuilder->getForm(MyForm::class);
    return $form;

    // // Or return a render array.
    // // in mytheme.html.twig use {{ form }} and {{ data }}.
    // return [
    //   '#theme' => 'mytheme',
    //   "#form" => $form,
    //   "#data" => $data,
    // ];
  }

}
Related