{"id":60195,"date":"2024-02-02T11:14:20","date_gmt":"2024-02-02T05:44:20","guid":{"rendered":"https:\/\/www.tothenew.com\/blog\/?p=60195"},"modified":"2024-02-02T11:19:53","modified_gmt":"2024-02-02T05:49:53","slug":"custom-webform-submit-handler","status":"publish","type":"post","link":"https:\/\/www.tothenew.com\/blog\/custom-webform-submit-handler\/","title":{"rendered":"Custom webform submit handler"},"content":{"rendered":"<h2>Overview<\/h2>\n<p>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.<\/p>\n<h2>Processing Form Submissions<\/h2>\n<p>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.<\/p>\n<h2>Executing Custom Logic<\/h2>\n<p>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.<\/p>\n<h2>Integration with Third-party Services<\/h2>\n<p>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.<\/p>\n<h2>Implementing Business Logic<\/h2>\n<p>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.<\/p>\n<h2>Customization and Extensibility<\/h2>\n<p>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.<\/p>\n<h2>Creating a custom webform handler<\/h2>\n<p>You\u2019ll first need to create a new custom module or have an existing module that you\u2019d like to put the handler in to.<\/p>\n<p>Here we\u2019ll outline what\u2019s needed for a standalone module.<\/p>\n<p>You\u2019ll need the following folder structure:<\/p>\n<pre>  \u25be modules\/\r\n    \u25be custom\/\r\n      \u25be ttn_custom_webform_handler\/\r\n        \u25be src\/\r\n          \u25be Plugin\/\r\n            \u25be WebformHandler\/\r\n<\/pre>\n<p>You\u2019ll then need to add the handler file in the WebformHandler directory. In this case, it\u2019s called TothenewWebformHandler.php and has this content:<\/p>\n<pre>&lt;?php \r\nnamespace Drupal\\ttn_custom_webform_handler\\Plugin\\WebformHandler; \r\nuse Drupal\\Component\\Utility\\Xss; \r\nuse Drupal\\Core\\Form\\FormStateInterface; \r\nuse Drupal\\Core\\Render\\Markup; \r\nuse Drupal\\webform\\Plugin\\WebformHandlerBase; \r\nuse Drupal\\webform\\WebformInterface; \r\nuse Drupal\\webform\\WebformSubmissionInterface; \r\nuse Symfony\\Component\\DependencyInjection\\ContainerInterface; \r\n\r\n\/** \r\n * TTN Custom Webform Handler. \r\n * \r\n * @WebformHandler( \r\n *   id = \"ttn_webform_handler\", \r\n *   label = @Translation(\"TTN Webform Handler\"), \r\n *   category = @Translation(\"TTN Webform Handler\"), \r\n *   description = @Translation(\"TTN custom webform submission handler.\"), \r\n *   cardinality = \\Drupal\\webform\\Plugin\\WebformHandlerInterface::CARDINALITY_SINGLE, \r\n *   results = \\Drupal\\webform\\Plugin\\WebformHandlerInterface::RESULTS_IGNORED, \r\n *   submission = \\Drupal\\webform\\Plugin\\WebformHandlerInterface::SUBMISSION_REQUIRED, \r\n * ) \r\n *\/ \r\nclass TtnCustomWebformHandler extends WebformHandlerBase { \r\n  \/** \r\n   * The token manager. \r\n   * \r\n   * @var \\Drupal\\webform\\WebformTokenManagerInterface \r\n   *\/ \r\n  protected $tokenManager; \r\n\r\n  \/** \r\n   * {@inheritdoc} \r\n   *\/ \r\n  public static function create(\r\n    ContainerInterface $container, \r\n    array $configuration, \r\n    $plugin_id, \r\n    $plugin_definition) { \r\n    $instance = parent::create($container, $configuration, $plugin_id, $plugin_definition); \r\n    $instance-&gt;tokenManager = $container-&gt;get('webform.token_manager');\r\n    return $instance;\r\n  }\r\n\r\n  \/**\r\n   * {@inheritdoc}\r\n   *\/\r\n  public function defaultConfiguration() {\r\n    return [\r\n      'message' =&gt; 'This is a custom message.',\r\n    ];\r\n  }\r\n\r\n  \/**\r\n   * {@inheritdoc}\r\n   *\/\r\n  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {\r\n    $form['message'] = [\r\n      '#type' =&gt; 'fieldset',\r\n      '#title' =&gt; $this-&gt;t('Message settings'),\r\n    ];\r\n    $form['message']['message'] = [\r\n      '#type' =&gt; 'textfield',\r\n      '#title' =&gt; $this-&gt;t('Message to be displayed when form is completed'),\r\n      '#default_value' =&gt; $this-&gt;configuration['message'],\r\n      '#required' =&gt; TRUE,\r\n    ];\r\n    return $this-&gt;setSettingsParents($form);\r\n  }\r\n\r\n  \/**\r\n   * {@inheritdoc}\r\n   *\/\r\n  public function submitConfigurationForm(array &amp;$form, FormStateInterface $form_state) {\r\n    parent::submitConfigurationForm($form, $form_state);\r\n    $this-&gt;configuration['message'] = $form_state-&gt;getValue('message');\r\n  }\r\n\r\n  \/**\r\n   * {@inheritdoc}\r\n   *\/\r\n  public function alterElements(array &amp;$elements, WebformInterface $webform) {\r\n    $this-&gt;debug(__FUNCTION__);\r\n  }\r\n\r\n  \/**\r\n   * {@inheritdoc}\r\n   *\/\r\n  public function overrideSettings(array &amp;$settings, WebformSubmissionInterface $webform_submission) {\r\n    $this-&gt;debug(__FUNCTION__);\r\n  }\r\n\r\n  \/**\r\n   * {@inheritdoc}\r\n   *\/\r\n  public function alterForm(array &amp;$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {\r\n    $this-&gt;debug(__FUNCTION__);\r\n  }\r\n\r\n  \/**\r\n   * {@inheritdoc}\r\n   *\/\r\n  public function validateForm(array &amp;$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {\r\n    $this-&gt;debug(__FUNCTION__);\r\n    if ($value = $form_state-&gt;getValue('element')) {\r\n      $form_state-&gt;setErrorByName('element', $this-&gt;t('The element must be empty. You entered %value.', ['%value' =&gt; $value]));\r\n    }\r\n  }\r\n\r\n  \/**\r\n   * {@inheritdoc}\r\n   *\/\r\n  public function submitForm(array &amp;$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {\r\n    $this-&gt;debug(__FUNCTION__);\r\n  }\r\n\r\n  \/**\r\n   * {@inheritdoc}\r\n   *\/\r\n  public function confirmForm(array &amp;$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {\r\n    $message = $this-&gt;configuration['message'];\r\n    $message = $this-&gt;replaceTokens($message, $this-&gt;getWebformSubmission());\r\n    $this-&gt;messenger()-&gt;addStatus(Markup::create(Xss::filter($message)), FALSE);\r\n    $this-&gt;debug(__FUNCTION__);\r\n  }\r\n\r\n  \/**\r\n   * {@inheritdoc}\r\n   *\/\r\n  public function preCreate(array &amp;$values) {\r\n    $this-&gt;debug(__FUNCTION__);\r\n  }\r\n\r\n  \/**\r\n   * {@inheritdoc}\r\n   *\/\r\n  public function postCreate(WebformSubmissionInterface $webform_submission) {\r\n    $this-&gt;debug(__FUNCTION__);\r\n  }\r\n\r\n  \/**\r\n   * {@inheritdoc}\r\n   *\/\r\n  public function postLoad(WebformSubmissionInterface $webform_submission) {\r\n    $this-&gt;debug(__FUNCTION__);\r\n  }\r\n\r\n  \/**\r\n   * {@inheritdoc}\r\n   *\/\r\n  public function preDelete(WebformSubmissionInterface $webform_submission) {\r\n    $this-&gt;debug(__FUNCTION__);\r\n  }\r\n\r\n  \/**\r\n   * {@inheritdoc}\r\n   *\/\r\n  public function post $this-&gt;configuration['debug'] = (bool) $form_state-&gt;getValue('debug');Delete(WebformSubmissionInterface $webform_submission) {\r\n    $this-&gt;debug(__FUNCTION__);\r\n  }\r\n\r\n  \/**\r\n   * {@inheritdoc}\r\n   *\/\r\n  public function preSave(WebformSubmissionInterface $webform_submission) {\r\n    $this-&gt;debug(__FUNCTION__);\r\n  }\r\n\r\n  \/**\r\n   * {@inheritdoc}\r\n   *\/\r\n  public function postSave(WebformSubmissionInterface $webform_submission, $update = TRUE) {\r\n    $this-&gt;debug(__FUNCTION__, $update ? 'update' : 'insert');\r\n  }\r\n\r\n  \/**\r\n   * {@inheritdoc}\r\n   *\/\r\n  public function preprocessConfirmation(array &amp;$variables) {\r\n    $this-&gt;debug(__FUNCTION__);\r\n  }\r\n\r\n  \/**\r\n   * {@inheritdoc}\r\n   *\/\r\n  public function createHandler() {\r\n    $this-&gt;debug(__FUNCTION__);\r\n  }\r\n\r\n  \/**\r\n   * {@inheritdoc}\r\n   *\/\r\n  public function updateHandler() {\r\n    $this-&gt;debug(__FUNCTION__);\r\n  }\r\n\r\n  \/**\r\n   * {@inheritdoc}\r\n   *\/\r\n  public function deleteHandler() {\r\n    $this-&gt;debug(__FUNCTION__);\r\n  }\r\n\r\n  \/**\r\n   * {@inheritdoc}\r\n   *\/\r\n  public function createElement($key, array $element) {\r\n    $this-&gt;debug(__FUNCTION__);\r\n  }\r\n\r\n  \/**\r\n   * {@inheritdoc}\r\n   *\/\r\n  public function updateElement($key, array $element, array $original_element) {\r\n    $this-&gt;debug(__FUNCTION__);\r\n  }\r\n\r\n  \/**\r\n   * {@inheritdoc}\r\n   *\/\r\n  public function deleteElement($key, array $element) {\r\n    $this-&gt;debug(__FUNCTION__);\r\n  }\r\n\r\n  \/**\r\n   * Display the invoked plugin method to end user.\r\n   *\r\n   * @param string $method_name\r\n   *   The invoked method name.\r\n   * @param string $context1\r\n   *   Additional parameter passed to the invoked method name.\r\n   *\/\r\n  protected function debug($method_name, $context1 = NULL) {\r\n    if (!empty($this-&gt;configuration['debug'])) {\r\n      $t_args = [\r\n        '@id' =&gt; $this-&gt;getHandlerId(),\r\n        '@class_name' =&gt; get_class($this),\r\n        '@method_name' =&gt; $method_name,\r\n        '@context1' =&gt; $context1,\r\n      ];\r\n      $this-&gt;messenger()-&gt;addWarning($this-&gt;t('Invoked @id: @class_name:@method_name @context1', $t_args), TRUE);\r\n    }\r\n  }\r\n\r\n}\r\n<\/pre>\n<p>Enable the module and clear the cache. Now, in your webform back-end, go to settings and then emails\/handlers <strong>(\/admin\/structure\/webform\/manage\/\/handlers)<\/strong>. Add your handler here.<\/p>\n<p><img decoding=\"async\" src=\"\/blog\/wp-ttn-blog\/uploads\/2024\/02\/ttn_custom_webform_handler.png\" alt=\"\" \/><\/p>\n<h2>Conclusion<\/h2>\n<p>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.<\/p>\n<p>Check out our other blog posts for more insights. Happy reading!<\/p>\n<div class=\"ap-custom-wrapper\"><\/div><!--ap-custom-wrapper-->","protected":false},"excerpt":{"rendered":"<p>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, [&hellip;]<\/p>\n","protected":false},"author":1700,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"iawp_total_views":723},"categories":[3602],"tags":[5261,3601,4884],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/60195"}],"collection":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/users\/1700"}],"replies":[{"embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/comments?post=60195"}],"version-history":[{"count":2,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/60195\/revisions"}],"predecessor-version":[{"id":60198,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/60195\/revisions\/60198"}],"wp:attachment":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/media?parent=60195"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/categories?post=60195"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/tags?post=60195"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}