How to Modify Form Action in Drupal

I'll show you the secret sauce to modifying a form action in Drupal using Webform and make the form submit properly.

How to modify form action pointing to form action in DrupalHow to modify form action pointing to form action in Drupal
Picture of the author John Siciliano
Published
Updated
Some of my content contains affiliate links – about

I recently found myself in a unique position where I needed to modify a form action to be an absolute URL in Drupal.

The quick backstory is I am using Cloudflare to serve a subdomain as a subdirectory. The subdomain is Drupal, and the main website is WordPress. Therefore Drupal is getting served on certain paths on my WordPress website. The problem is the Cloudflare proxy setup only accepts GET requests.

The form I am trying to modify is built with Webform.

Note: You may embed the Webform module using the share feature, although this wouldn't suffice for my use case as I needed to tie the submission to the node it was submitted on.

I needed a way to send POST requests to my Drupal URL, which led me needing to modify the form action to use the same path but add the domain to it (pointing to the original URL).

I first tried modifying the form action in hook_form_alter but was unsuccessful. While it modifies the action, it messes something up in the form and doesn't submit. The forms use some placeholder in the action at that stage in the rendering process, and changing it disrupts its flow.

I was at a loss. But Jacob, known as Jrockowitz online, and better known as THE creator of the Drupal webform module, was intrigued by this unique use case and lent a helping hand.

The Solution

Here is how you modify a Webform's action in Drupal:

/**
 * Implements hook_preprocess_webform().
 */
function MYMODULE_preprocess_webform(array &$variables) {
  $variables['attributes']['action'] = \Drupal::request()->getSchemeAndHttpHost() . $variables['attributes']['action'];
}

Implement this, and the form action will be an absolute URL pointing to the origin (or change the value to match your use case).

The form submits!

You need to set up submission handling and determine where it redirects to after submission.

Happy form building and modifying form actions in Drupal!

The Solution (Video)

John Siciliano
WebsiteWebsite Creator
MagnetGrowth Marketer
BracketsDeveloper
Diamond on BlogContent Creator
I spend my time creating stuff online and documenting it to help others (and earn a living). My focus areas include website builders, CMSs, marketing, and development.