How to Programmatically Display Form in Custom Block in Drupal 8

| | 2 min read

Most often we may want to show our custom forms in blocks. Here are the simple steps to accomplish this.

In the below code we will create a form called “MymoduleExampleForm” and this form will be placed in a custom block called “MymoduleExampleBlock”.

Step 1 – Create a custom module say 'mymodule'. For details on how to create a custom module in Drupal 8 See here

Step 2 – Create a php file named MymoduleExampleForm.php in mymodule/src/Form and place the following code.


  <?php

    namespace Drupal\mymodule\Form;
    use Drupal\Core\Form\FormBase;
    use Drupal\Core\Form\FormStateInterface;
    /**
     * Class MymoduleExampleForm for demonstration.
    */
    class MymoduleExampleForm extends FormBase {
      /**
       * {@inheritdoc}
      */
      public function getFormId() {
        return 'mymodule_example_form';
      }
      /**
       * {@inheritdoc}
      */
      public function buildForm(array $form, FormStateInterface $form_state) {
        $form['user_mail'] = [
          '#type' => 'email',
          '#title' => t('Email ID:'),
          '#required' => TRUE,
        ];
        $form['actions']['#type'] = 'actions';
        $form['actions']['submit'] = [
         '#type' => 'submit',
         '#value' => $this->t('Subscribe'),
        ];
        return $form;
      }
      /**
       * {@inheritdoc}
      */
      public function validateForm(array &$form, FormStateInterface $form_state) {
        // Nothing.
      }
      /**
       * {@inheritdoc}
      */
      public function submitForm(array &$form, FormStateInterface $form_state) {
        drupal_set_message($this->t('@user_email ,Your email-id has been sent !', ['@user_email' => $form_state-  >getValue('user_mail')]));}
    }

 

Step 3 – Create a php file named MymoduleExampleBlock.php in mymodule/src/Plugin/Block and place the following code.


  <?php

    namespace Drupal\mymodule\Plugin\Block;

    use Drupal\Core\Block\BlockBase;

    /**
     * Provides a 'MymoduleExampleBlock' block.
     *
     * @Block(
     *   id = "mymodule_example_block",
     *   admin_label = @Translation("Example block"),
     *   category = @Translation("Custom example block")
     * )
    */
    class MymoduleExampleBlock extends BlockBase {

     /**
      * {@inheritdoc}
     */
     public function build() {

       $form = \Drupal::formBuilder()->getForm('Drupal\mymodule\Form\MymoduleExampleForm');

       return $form;
     }
   }