In this Tutorial we learn how to make a a custom block and render a form in a block in drupal 8 customization process.

So lets start 

1) Create a basic simple module by create .info.yml file as below:

name: Custom form in Block
description: key2goal example module for form in block
type: module
core: 8.x
package: Custom

2) Now create the form in src/Form/KeyForm.php as below:

<?php
/**
 * @file
 * Contains \Drupal\custom_form_in_block\Form\KeyForm.
 */
namespace Drupal\custom_form_in_block\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

class keyForm extends FormBase {
  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'key_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {

    $form['name'] = array(
      '#type' => 'textfield',
      '#title' => t('Name:'),
      '#required' => TRUE,
    );

    $form['mail'] = array(
      '#type' => 'email',
      '#title' => t('Email ID:'),
      '#required' => TRUE,
    );

    $form['actions']['#type'] = 'actions';
    $form['actions']['submit'] = array(
      '#type' => 'submit',
      '#value' => $this->t('Submit'),
    );
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {

    drupal_set_message($this->t('Hello @name ,Your @email is being submitted!', array('@name' => $form_state->getValue('name'),'@email' => $form_state->getValue('mail'))));

  }
}

3) Finally create the Block in src/Plugin/Block/FormBlock.php as below:

<?php
/**
 * @file
 * Contains \Drupal\custom_form_in_block\Plugin\Block\FormBlock.
 */

namespace Drupal\custom_form_in_block\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Form\FormInterface;

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

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

    $form = \Drupal::formBuilder()->getForm('Drupal\custom_form_in_block\Form\KeyForm');

    return $form;
   }
}

4) Now enable the module and search custom block with form name " Form block" and placed at any region that using Drupal Block layout.

Github URLhttps://github.com/key2goal/custom-form-block-drupal-8