Webforms with Custom Templates in Drupal 7

Webform is basically the standard module for creating custom forms in Drupal. By default Webforms are treated as editorial content and therefore just have an automatically created id (like nodes). However most of the time you want to be able to create forms in a local environment and deploy them to your live website. Today I will explain you how.

First you will need to install another module: Webform Features. This enables you to export Webforms as a feature using the Features module. After installing Webform Features, you can assign machine-readable names to your form.

Webform creation form with machine-readable name.
Webform creation form with machine-readable name.

Afterwards you can select the created form from the feature creation form. Please note: That machine-readable names need to be unique. They will be created automatically when you create a new webform, but can be also edited manually.

Webform in feature creation dialog.
Webform in feature creation dialog.

Custom template

You might also want to create a custom template for your webform. Unfortunately you can only create templates for certain node ids and you can't even change this behaviour with theme_hook_suggestions, as the Webform module restricts template names with a pattern. There was an approach to change this, but the Webform guys were pretty stubborn about this issue.

So you basically need to use a patch for this:

diff --git a/webform.module b/webform.module
index c5c1802..ad72360 100644
--- a/webform.module
+++ b/webform.module
@@ -625,7 +625,6 @@ function webform_theme() {
     'webform_form' => array(
       'render element' => 'form',
       'template' => 'templates/webform-form',
-      'pattern' => 'webform_form_[0-9]+',
     ),
     'webform_confirmation' => array(
       'variables' => array('node' => NULL, 'sid' => NULL),

Afterwards you can assign your own theme_hook_suggestions from within your template.php or a custom module. You can actually use any name you want. The suggestions below comply with the Drupal standards.

function YOUR_THEME_preprocess_webform_form(array &$variables) {
  $node = $variables['form']['#node'];
  if (isset($node->webform['machine_name'])) {
    $machine_name = $node->webform['machine_name'];
    $variables['theme_hook_suggestions'][] = 'webform_form__' . $machine_name;
  }
}

Finally you are able to create a deployable, individual template for every single webform.

But what about Drupal 8?

In Drupal 8 Webforms can be exported through configuration. So there is no need for the Webform Features module anymore.


Comments


Important: By clicking on the checkbox above you explicitly agree to the transfer of data to Facebook. The consent is given once for the comments of this article and will not be stored. Further details can be found in the Social Plugins section of the Privacy Policy.