Form

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.

 

How to handle form submission using AJAX in Drupal 8

Here is the buildForm function for creating an AJAX form.

  public function buildForm(array $form, FormStateInterface $form_state) {
  
    $form = [];
    $form['email'] = [
      '#type' => 'textfield', 
      '#attributes' => ['placeholder'=>'Enter your Email ID'],
      '#description' => 'Submit your email address to recieve updates',
      '#size' => 100,
      '#maxlength' => 150,
      '#required' => TRUE,  
    ];

    $form['submit_button'] = [
      '#type' => 'submit',
      '#name' => 'submit-email',
      '#value' => '>',
      '#ajax' => [
        'callback' => '::processEmail',
        'wrapper' => 'thanks-message',
        'effect' => 'fade',
        'event' => 'click',
        'progress' => [
          'type' => 'throbber',
          'message' => $this->t('Processing ...'),
        ],
      ],
    ];

    $form['thanks'] = [
     '#type' => '#markup',
     '#markup'=> '',
     '#prefix' => '<div id="thanks-message">',
     '#suffix' => '</div>'
    ];

    $form['error'] = [
     '#type' => '#markup',
     '#markup'=> '',
     '#prefix' => '<div id="error-message">',
     '#suffix' => '</div>'
   ];

    return $form;
  }

And this the code for callback function.

  public function processEmail (array &$form, FormStateInterface $form_state) {
    $form['#cache'] = ['max-age' => 0];
    $email = $form_state->getValue('email');
    $renderer = \Drupal::service('renderer');
    $response = new AjaxResponse();

    if (!(\Drupal::service('email.validator')->isValid($email))) {
      $elem = [
        '#type' => 'markup',
        '#markup'=> 'Please provide correct Email ID',
        '#prefix' => '<div id="error-message">',
        '#suffix' => '</div>'
      ];
      $response->addCommand(new InsertCommand('#error-message', $renderer->render($elem)));
      return $response;
    }
    else {
      $element = [
        '#type' => 'markup',
        '#markup'=> 'Thank you! Please check your email for confirmation message.',
        '#prefix' => '<div id="thanks-message">',
        '#suffix' => '</div>'
      ];

      $error = [
        '#type' => 'markup',
        '#markup'=> '',
        '#prefix' => '<div id="error-message">',
        '#suffix' => '</div>'
      ];

      //$elma used as an empty variable to hide unwanted element.s

      $response->addCommand(new ReplaceCommand('#thanks-message', $renderer->render($element)));
      $response->addCommand(new ReplaceCommand('#edit-submit-button', $renderer->render($elema)));
      $response->addCommand(new ReplaceCommand('#edit-email--description', $renderer->render($elema)));
      $response->addCommand(new ReplaceCommand('#edit-email', $renderer->render($elema)));
      $response->addCommand(new RemoveCommand('#error-message'));
      return $response;
    }
  }

How to handle form submission using JS in Drupal 7

In Drupal 7 you use behaviors to handle the form submission. It can be achieved in following way.

  $form = array();
  $form['sample_value'] = array(
    '#type' => 'textfield',
    '#title' => 'Sample Value',
    '#size' => 20,
    '#maxlength' => 150,
    '#required' => TRUE,
  );

 //Make sure you set Drupal form submission to be false.

  $form['#executes_submit_callback'] = FALSE;

  $form['submit_button'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );

 //Attach the JS file to form.

$form['#attached']['js'][] = drupal_get_path('module', 'custom_module') . '/js/custom.js';

Now in your JS file, you can access the values in following ways 

/**
 * @file Javascript behaviors for the Custom module.
 */

(function ($) {
  // Make sure our objects are defined.
  Drupal.CustomForm = Drupal.CustomForm || {};

  Drupal.CustomForm.compute = function(form) {
     //You can perform any kind of operation from value variable. 

     value = form.sample_value;
  }

  Drupal.behaviors.custom = {
    attach: function (context, settings) {

      $("#edit-submit-button", context).click(function(event) {
        Drupal.CustomForm.compute(this.form);
        return false;
      });
    }
  };
})(jQuery);

How to create controller which provides filter and results alongside

 In Drupal 8 a filter is nothing but a form, it can be displayed above results provided by controller in following way.

//Getting form markup in $form variable.Replace example_drupalabc with your custom module.
$form = \Drupal::formBuilder()->getForm('Drupal\example_drupalabc\Form\FilterForm');
//Adding $form in $build array.
$build['filter'] = $form;
//Now your controller can add other data in various ways.Some of them are:
$build['links'] = [ 'data' => [ '#type' => 'operations', '#links' => $links, ],
];
$build['requests_table'] = [ '#theme' => 'table', '#rows' => $rows, '#header' => $header,
];
//You can also add a pager.
$build['pager'] = [ '#type' => 'pager', '#weight' => 100,
];
//Don't forget to return $build.
return $build;

 

 

How to redirect to a page after form submit in Drupal 8

You can redirect the user to any page after form submission in the following way.

//Don't forget to include this in beginning. This will only work in submitForm function.
use Drupal\Core\Url;
//Constructing a URL.Will redirect to example-page with query paramter q = 5.
$response = Url::fromUserInput('/example-page?q=5');
$form_state->setRedirectUrl($response);

 

How to create block with Form in Drupal 8

Blocks are the most important site building elements of Drupal 8. Many times there is a requirement of form in a block. It can be placed in following way. 

<?php
//Namespace for Example DrupalABC module.Replace it with your custom module.
namespace Drupal\example_drupalabc\Plugin\Block;
use Drupal\Core\Block\BlockBase;
/**
* Provides a 'HomePageSearchBlock' block.
*
* @Block( * id = "homepage_search_block",
* admin_label = @Translation("Home Page search block"),
* )
*/
class HomePageSearchBlock extends BlockBase {
public function build() {
$build = [];
$build['#cache']['contexts'][] = 'url';
$build['#cache']['max-age'] = 864000; $build['homepage_search_filter_block']['form'] = \Drupal::formBuilder() ->getForm('\Drupal\example_drupalabc\Form\HomePageSearchForm');
return $build;
}
}