Drupal 8 : Custom Form Validate and Submit in hook_form_alter() with Example

In Drupal 8 we can able to call custom validate and submit function for our need. This custom functions need to be defined in hook_form_alter(). Validate is defined as array parameter for #validate key of $form array. Similarly for submit is defined as array parameter for #submit on $form submit action.

Syntax:

function hook_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  // Custom validate function.
  $form['#validate'][] = ‘MYMODULE_CUSTOM_VALIDATE’;
 
  // Custom submit function.
  $form['actions']['submit']['#submit'][] = 'MYMODULE_CUSTOM_SUBMIT';
}

Example:

use Drupal\Core\Form\FormStateInterface;
.........
.........
/**
 * Implements hook_form_FORM_ID_alter().
 */
function faq_ask_form_node_faq_form_alter(&$form, FormStateInterface $form_state) {
  // Custom validate function.
  $form['#validate'][] = 'faq_ask_form_validate';
   // Custom Submit function.
  $form['actions']['submit']['#submit'][] = 'faq_ask_submit';
}
 
/**
 * Validation form for the FAQ Ask form.
 *
 * Verifies that the e-mail entered seems to be a valid e-mail.
 */
function faq_ask_form_validate($form, FormStateInterface &$form_state) {
  $email = $form_state->getValue('faq_email');
  if (isset($email) && 2 < strlen($email)) {
    if (!valid_email_address($email)) {
      $form_state->setErrorByName('email', t('That is not a valid e-mail address.'));
    }
  }
}
 
/**
 * Handles the ask form submission.
 */
function faq_ask_submit($form, FormStateInterface $form_state) {
  $user = \Drupal::currentUser();
  if ($user->hasPermission('ask question') && !$user->hasPermission('answer question')) {
    $node_id = $form_state->getValue('nid');
    $node = node_load($node_id);
    if (is_object($node)) {
      $node->status->value = 0;
      $node->save();
    }
  }
}
Category: