Create a webform submit Handler

Last updated on 23/09/2019

A Webform submit handler must be integrated as a Plugin extending WebformHandlerBase.

To create for example a handler which is going to redirect to a specific page based on submitted data you'll have to create a plugin located on my_module/src/Plugin/WebformHandler/MyModuleRedirect.php

namespace Drupal\my_module\Plugin\WebformHandler;
 
use Drupal\Core\Form\FormStateInterface;
use Drupal\webform\Plugin\WebformHandlerBase;
use Drupal\webform\WebformSubmissionInterface;
 
/**
 * Form submission handler.
 *
 * Redirects to the [...] after the submit.
 *
 * @WebformHandler(
 *   id = "my_module_redirect",
 *   label = @Translation("Redirect to the ..."),
 *   category = @Translation("Webform Handler"),
 *   description = @Translation("Redirect to the ..."),
 *   cardinality = \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_SINGLE,
 *   results = \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_PROCESSED,
 * )
 */
class MyModuleRedirect extends WebformHandlerBase {
 
  public function confirmForm(array &$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {
 
    $values = $webform_submission->getData();
 
    if (!empty($values['some_data'])) {
      $form_state->setRedirect('some_route.view', [
        'some_id' => $values['some_data'],
      ]);
    }
 
  }
}

Adding the handler programmatically to the Webform

As most of the times webforms are excluded from Config Import, the following code can be used in a HOOK_update() to attach the handler to the Webform.

/**
 * Implements hook_update().
 */
function my_module_update_8001() {
 
  /** @var \Drupal\webform\Plugin\WebformHandlerManagerInterface $handler_manager */
  $handler_manager = \Drupal::service('plugin.manager.webform.handler');
  $webformStorage = \Drupal::entityTypeManager()->getStorage('webform');
 
  // Define 'my_module_redirect' webform handler configuration.
  $handlerConfiguration = [
    'id' => 'my_module_redirect',
    'label' => 'Redirect to the ...',
    'handler_id' => 'my_module_redirect',
    'status' => 1,
    'weight' => 1,
    'settings' => [],
  ];
 
  foreach ($webformStorage->loadMultiple() as $webform) {
    $webformIds = ['webform_name_1', 'webform_name_2'];
    if (in_array($webform->id(), $webformIds, TRUE)) {
      $handler = $handler_manager->createInstance('my_module_redirect', $handlerConfiguration);
      $webform->setOriginalId($webform->id());
      $webform->addWebformHandler($handler);
    }
  }
 
}