Custom webform submit handler

02 / Feb / 2024 by Radheshyam Kumawat 0 comments

Overview

In Drupal, a Webform handler is a component of the Webform module that processes form submissions. Webform handlers allow developers to extend the functionality of webforms by performing various actions or integrations upon form submission.

Processing Form Submissions

When a user submits a webform, the form data is passed through a series of handlers, which can perform various actions such as sending emails, storing data, integrating with external services, etc.

Executing Custom Logic

Handlers can execute custom PHP logic to process form submissions in a specific way. This might involve data validation, manipulation, or any other custom processing needed for the form data.

Integration with Third-party Services

Handlers can integrate webforms with external services such as CRM systems, mailing lists, analytics platforms, etc. This allows developers to automate tasks and streamline workflows.

Implementing Business Logic

Handlers can enforce business rules and logic related to form submissions. For example, a handler might check if certain conditions are met before processing the form data further.

Customization and Extensibility

Webform handlers provide a flexible and extensible framework for customizing the behavior of webforms. Developers can create custom handlers to implement specific functionality tailored to their project requirements.

Creating a custom webform handler

You’ll first need to create a new custom module or have an existing module that you’d like to put the handler in to.

Here we’ll outline what’s needed for a standalone module.

You’ll need the following folder structure:

  ▾ modules/
    ▾ custom/
      ▾ ttn_custom_webform_handler/
        ▾ src/
          ▾ Plugin/
            ▾ WebformHandler/

You’ll then need to add the handler file in the WebformHandler directory. In this case, it’s called TothenewWebformHandler.php and has this content:

<?php 
namespace Drupal\ttn_custom_webform_handler\Plugin\WebformHandler; 
use Drupal\Component\Utility\Xss; 
use Drupal\Core\Form\FormStateInterface; 
use Drupal\Core\Render\Markup; 
use Drupal\webform\Plugin\WebformHandlerBase; 
use Drupal\webform\WebformInterface; 
use Drupal\webform\WebformSubmissionInterface; 
use Symfony\Component\DependencyInjection\ContainerInterface; 

/** 
 * TTN Custom Webform Handler. 
 * 
 * @WebformHandler( 
 *   id = "ttn_webform_handler", 
 *   label = @Translation("TTN Webform Handler"), 
 *   category = @Translation("TTN Webform Handler"), 
 *   description = @Translation("TTN custom webform submission handler."), 
 *   cardinality = \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_SINGLE, 
 *   results = \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_IGNORED, 
 *   submission = \Drupal\webform\Plugin\WebformHandlerInterface::SUBMISSION_REQUIRED, 
 * ) 
 */ 
class TtnCustomWebformHandler extends WebformHandlerBase { 
  /** 
   * The token manager. 
   * 
   * @var \Drupal\webform\WebformTokenManagerInterface 
   */ 
  protected $tokenManager; 

  /** 
   * {@inheritdoc} 
   */ 
  public static function create(
    ContainerInterface $container, 
    array $configuration, 
    $plugin_id, 
    $plugin_definition) { 
    $instance = parent::create($container, $configuration, $plugin_id, $plugin_definition); 
    $instance->tokenManager = $container->get('webform.token_manager');
    return $instance;
  }

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [
      'message' => 'This is a custom message.',
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $form['message'] = [
      '#type' => 'fieldset',
      '#title' => $this->t('Message settings'),
    ];
    $form['message']['message'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Message to be displayed when form is completed'),
      '#default_value' => $this->configuration['message'],
      '#required' => TRUE,
    ];
    return $this->setSettingsParents($form);
  }

  /**
   * {@inheritdoc}
   */
  public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
    parent::submitConfigurationForm($form, $form_state);
    $this->configuration['message'] = $form_state->getValue('message');
  }

  /**
   * {@inheritdoc}
   */
  public function alterElements(array &$elements, WebformInterface $webform) {
    $this->debug(__FUNCTION__);
  }

  /**
   * {@inheritdoc}
   */
  public function overrideSettings(array &$settings, WebformSubmissionInterface $webform_submission) {
    $this->debug(__FUNCTION__);
  }

  /**
   * {@inheritdoc}
   */
  public function alterForm(array &$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {
    $this->debug(__FUNCTION__);
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {
    $this->debug(__FUNCTION__);
    if ($value = $form_state->getValue('element')) {
      $form_state->setErrorByName('element', $this->t('The element must be empty. You entered %value.', ['%value' => $value]));
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {
    $this->debug(__FUNCTION__);
  }

  /**
   * {@inheritdoc}
   */
  public function confirmForm(array &$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {
    $message = $this->configuration['message'];
    $message = $this->replaceTokens($message, $this->getWebformSubmission());
    $this->messenger()->addStatus(Markup::create(Xss::filter($message)), FALSE);
    $this->debug(__FUNCTION__);
  }

  /**
   * {@inheritdoc}
   */
  public function preCreate(array &$values) {
    $this->debug(__FUNCTION__);
  }

  /**
   * {@inheritdoc}
   */
  public function postCreate(WebformSubmissionInterface $webform_submission) {
    $this->debug(__FUNCTION__);
  }

  /**
   * {@inheritdoc}
   */
  public function postLoad(WebformSubmissionInterface $webform_submission) {
    $this->debug(__FUNCTION__);
  }

  /**
   * {@inheritdoc}
   */
  public function preDelete(WebformSubmissionInterface $webform_submission) {
    $this->debug(__FUNCTION__);
  }

  /**
   * {@inheritdoc}
   */
  public function post $this->configuration['debug'] = (bool) $form_state->getValue('debug');Delete(WebformSubmissionInterface $webform_submission) {
    $this->debug(__FUNCTION__);
  }

  /**
   * {@inheritdoc}
   */
  public function preSave(WebformSubmissionInterface $webform_submission) {
    $this->debug(__FUNCTION__);
  }

  /**
   * {@inheritdoc}
   */
  public function postSave(WebformSubmissionInterface $webform_submission, $update = TRUE) {
    $this->debug(__FUNCTION__, $update ? 'update' : 'insert');
  }

  /**
   * {@inheritdoc}
   */
  public function preprocessConfirmation(array &$variables) {
    $this->debug(__FUNCTION__);
  }

  /**
   * {@inheritdoc}
   */
  public function createHandler() {
    $this->debug(__FUNCTION__);
  }

  /**
   * {@inheritdoc}
   */
  public function updateHandler() {
    $this->debug(__FUNCTION__);
  }

  /**
   * {@inheritdoc}
   */
  public function deleteHandler() {
    $this->debug(__FUNCTION__);
  }

  /**
   * {@inheritdoc}
   */
  public function createElement($key, array $element) {
    $this->debug(__FUNCTION__);
  }

  /**
   * {@inheritdoc}
   */
  public function updateElement($key, array $element, array $original_element) {
    $this->debug(__FUNCTION__);
  }

  /**
   * {@inheritdoc}
   */
  public function deleteElement($key, array $element) {
    $this->debug(__FUNCTION__);
  }

  /**
   * Display the invoked plugin method to end user.
   *
   * @param string $method_name
   *   The invoked method name.
   * @param string $context1
   *   Additional parameter passed to the invoked method name.
   */
  protected function debug($method_name, $context1 = NULL) {
    if (!empty($this->configuration['debug'])) {
      $t_args = [
        '@id' => $this->getHandlerId(),
        '@class_name' => get_class($this),
        '@method_name' => $method_name,
        '@context1' => $context1,
      ];
      $this->messenger()->addWarning($this->t('Invoked @id: @class_name:@method_name @context1', $t_args), TRUE);
    }
  }

}

Enable the module and clear the cache. Now, in your webform back-end, go to settings and then emails/handlers (/admin/structure/webform/manage//handlers). Add your handler here.

Conclusion

Overall, Webform handlers are a powerful feature of the Drupal Webform module, enabling developers to create sophisticated and customized forms with a wide range of functionalities and integrations.

Check out our other blog posts for more insights. Happy reading!

FOUND THIS USEFUL? SHARE IT

Leave a Reply

Your email address will not be published. Required fields are marked *