This tutorial explains how to develop a custom webform handler for Drupal 8’s Webform module. The guide demonstrates the process of creating a handler to transmit form submissions to third-party services.

Module Structure

Start by establishing this directory hierarchy:

modules/
  custom/
    my_custom_form_handler/
      src/
        Plugin/
          WebformHandler/

Basic Handler Template

The handler file (ExampleFormHandler.php) requires these use statements and class definition:

<?php
namespace Drupal\my_custom_form_handler\Plugin\WebformHandler;

use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Serialization\Yaml;
use Drupal\Core\Form\FormStateInterface;
use Drupal\webform\Plugin\WebformHandlerBase;
use Drupal\webform\WebformSubmissionInterface;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;

/**
 * @WebformHandler(
 *   id = "example_form_handler",
 *   label = @Translation("Example form handler"),
 *   category = @Translation("Examples"),
 *   description = @Translation("An example form handler"),
 * )
 */
class ExampleFormHandler extends WebformHandlerBase {
  public function submitForm(
    array &$form,
    FormStateInterface $form_state,
    WebformSubmissionInterface $webform_submission
  ) {
    // Implementation here
  }
}

Sending Data to Third Parties

The implementation uses Guzzle HTTP client to post submission data:

public function submitForm(
  array &$form,
  FormStateInterface $form_state,
  WebformSubmissionInterface $webform_submission
) {
  $client = \Drupal::httpClient();
  $response = $client->request('POST',
    'https://<your_third_party_service>',
    [
      'form_params' => [
        'first_name' => $webform_submission->getData('first_name')
      ]
    ]
  );

  $code = $response->getStatusCode();
  if ($code >= 400 || $code === 0) {
    // Error handling logic
  }
}

With this handler in place, any form submission will trigger a POST request to your specified third-party service with the form data.