To build a form using block module, you can easily use [Webform module][1] where you can add a form and display as a block.
----------
If you mean to create a form programatically in the custom block, you can achieve that by creating two files shown below:
Form file (`src/Form/DemoForm.php`):
<?php
/**
* @file
* Contains \Drupal\demo\Form\DemoForm.
*/
namespace Drupal\demo\Form;
use Drupal\Core\Form\FormBase;
class DemoForm extends FormBase {
/**
* {@inheritdoc}.
*/
public function getFormId() {
return 'demo_form';
}
/**
* {@inheritdoc}.
*/
public function buildForm(array $form, array &$form_state) {
$form['email'] = array(
'#type' => 'email',
'#title' => $this->t('Your .com email address.')
);
$form['show'] = array(
'#type' => 'submit',
'#value' => $this->t('Submit'),
);
return $form;
}
/**
* {@inheritdoc}
*/
public function validateForm(array &$form, array &$form_state) {
$values = $form_state->getValues();
if (strpos($values['email'], '.com') === FALSE ) {
$form_state->setErrorByName('email', t('This is not a .com email address.'));
}
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, array &$form_state) {
drupal_set_message($this->t('Your email address is @email', array('@email' => $form_state['values']['email'])));
}
}
<sup>Source: [Building a Drupal 8 Module: Blocks and Forms][2].</sup>
Block file (`src/Plugin/Block/HelloBlock.php`):
<?php
namespace Drupal\mymodule\Plugin\Block;
use Drupal\Core\Block\BlockBase;
/**
* Provides a 'Hello' Block.
*
* @Block(
* id = "form_block",
* admin_label = @Translation("My form"),
* category = @Translation("My Category"),
* )
*/
class HelloBlock extends BlockBase {
/**
* {@inheritdoc}
*/
public function build() {
$form = \Drupal::formBuilder()->getForm('\Drupal\mymodule\Form\HelloBlock');
//$form['#attached']['js'][] = drupal_get_path('module', 'example') . '/js/example.js';
//$form['#markup'] = $this->t('Custom text');
return $form;
}
}
<sup>Source: [Create a custom block][3].</sup>
----------
To add a form to the *Block Configuration*, see: [Add a Form to the Block Configuration][4].
[1]:
[To see links please register here]
[2]:
[To see links please register here]
[3]:
[To see links please register here]
[4]:
[To see links please register here]