How to submit a form from another submit handler.

In some cases, we might want to modify the form submission behaviour to better fit a particular use case. For instance, we would like to offer our own submit handler, and we will contact the original submit handler under specific circumstances.

Here, we'll utilise the module name example to change the way a form submits when its form ID is demo_form, which is provided by demo module. To do this, we'll create the code that follows in example.module file:

<?php

/**
 * @file
 * Primary module hooks for example module.
 */

use Drupal\Core\Form\FormStateInterface;
use Drupal\demo\Form\DemoForm;

/**
 * Implements hook_form_FORM_ID_alter().
 */
function example_form_demo_form_alter(&$form, FormStateInterface &$form_state, $form_id) {
  $form['actions']['submit']['#submit'] = ['example_custom_submit_form'];
}

/**
 * Custom example submit handler.
 */
function example_custom_submit_form(&$form, FormStateInterface &$form_state) {

  // Call original form submit handler
  if (<certain condition>) {
    \Drupal::classResolver(DemoForm::class)->submitForm($form,  $form_state);
  }
  else {
    // Do stuff related to example submit handler.
  }
  
}
5.0/5