This CodeLet let you programmatically create a form page and render same form on a block. Create custom module and follow CodeLet instruction to create a form and block programmatically.
CodeLet
<?php
//Drupal8 form: let’s define our simple MyCustomForm class inside src/Form/MyCustomForm.php
/**
* @file
* Contains \Drupal\custom\Form\MyCustomForm.
*/
namespace Drupal\custom\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
/**
* My Custom form.
*/
class MyCustomForm extends FormBase {
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'my_custom_form';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$form['name'] = array(
'#type' => 'textfield',
'#size' => 15,
'#placeholder' => t('Name'),
);
$form['description'] = array(
'#type' => 'textarea',
'#required' => TRUE,
'#placeholder' => t('Description'),
);
$form['email'] = array(
'#type' => 'email',
'#required' => TRUE,
'#placeholder' => t('E-mail address'),
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Submit'),
);
return $form;
}
/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
if ($form_state->getValue('name') == '' ) {
$form_state->setErrorByName('name', t('This is a required field.'));
}
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$name = $form_state->getValue('name');
$description = $form_state->getValue('description');
$email = $form_state->getValue('email');
$message = t('Your information has been successfully submitted.') ;
drupal_set_message($message);
}
}
?>
<?php
// Drupal8 block: let’s define our simple CustomBlock class inside src/Plugin/Block/CustomBlock.php
// This "Custom Block" will be available at admin block interface you can place it on any region.
/**
* @file
* Contains \Drupal\custom\Plugin\Block\CustomBlock.
*/
namespace Drupal\custom\Plugin\Block;
use Drupal\Core\Block\BlockBase;
/**
* Provides Custom Block.
*
* @Block(
* id = "my_custom_block",
* admin_label = @Translation("Custom Block"),
* category = @Translation("Blocks")
* )
*/
class CustomBlock extends BlockBase {
/**
* {@inheritdoc}
*/
public function build() {
$build = array();
$build['#markup'] = '<h2>' . t('My Custom Form') . '</h2>';
$build['form'] = \Drupal::formBuilder()->getForm('Drupal\custom\Form\MyCustomForm');
return $build;
}
}
?>
Info file details
name: Custom module
description: 'Custom module for Enhance feature'
type: module
core: 8.x