In this post, I'll show you how to create custom validation/submit handler to an existing form in Drupal 8.
Custom validation handler
use Drupal\Core\Form\FormStateInterface;
/**
* Implements hook_form_FORM_ID_alter() for the FORM_ID() form.
*/
function mymodule_form_FORM_ID_alter(&$form, FormStateInterface $form_state, $form_id) {
$form['#validate'][] = '_mymodule_form_FORM_ID_validate';
}
/**
* Validates submission values in the FORM_ID() form.
*/
function _mymodule_form_FORM_ID_validate(array &$form, FormStateInterface $form_state) {
// Validation code here
}
Custom submit handler
use Drupal\Core\Form\FormStateInterface;
/**
* @param $form
* @param FormStateInterface $form_state
* @param $form_id
*/
function mymodule_form_node_form_alter(&$form, FormStateInterface $form_state, $form_id) {
foreach (array_keys($form['actions']) as $action) {
if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {
$form['actions'][$action]['#submit'][] = 'mymodule_form_submit';
}
}
}
/**
* @param array $form
* @param FormStateInterface $form_state
*/
function mymodule_form_submit(array $form, FormStateInterface $form_state){
// submit code here
}
Example: how to create custom validation/submit handler on user registration form.
/**
* Implements hook_form_form_id_form_alter().
*/
function mymodule_form_user_register_form_alter(&$form, &$form_state, $form_id) {
$form['#validate'][] = '_mymodule_user_register_validate';
$form['#submit'][] = '_mymodule_user_register_form_submit';
}
/**
* @param $form
* @param FormStateInterface $form_state
*/
function _mymodule_user_register_form_submit($form, FormStateInterface $form_state)
{
// submit code here
}
/**
* Custom validation function.
*
* Checks if the domain in the email address is on a list of allowed domains.
*/
function _mymodule_user_register_validate(&$form, &$form_state) {
// Validation code here
}