Advertising sustains the DA. Ads are hidden for members. Join today

Webform Cookbook

How to programmatically add a handler to a new webform

Last updated on
12 August 2017

Below is a recipe for programmatically adding a handler to a new webform.

use Drupal\webform\WebformInterface;

/**
 * Implements hook_ENTITY_TYPE_insert().
 */
function MODULE_webform_insert(WebformInterface $webform) {
  /** @var \Drupal\webform\Plugin\WebformHandlerManagerInterface $handler_manager */
  $handler_manager = \Drupal::service('plugin.manager.webform.handler');

  // Create webform handler.
  $handler_configuration = [
    'id' => 'remote_post',
    'label' => 'Remote Post',
    'handler_id' => 'remote_post',
    'status' => 1,
    'weight' => 0,
    'settings' => [],
  ];
  $handler = $handler_manager->createInstance('remote_post', $handler_configuration);

  // Must set original id so that the webform can be resaved.
  $webform->setOriginalId($webform->id());

  // Add webform handler which triggers Webform::save().
  $webform->addWebformHandler($handler);
}

Help improve this page

Page status: No known problems

You can: