Online forms are one of the most common methods used to gather meaningful information and connect with customers and prospects on your website. There’s always the need to add custom theming or functionality to your webforms in Drupal 7, and we’re going to cover a few different options that will equip you to bend webform to your will.
Theming options covered in this blog post:
- Theming elements via the Webform UI
- Theming elements via custom templates
- Altering a Webform with hook_form_alter()
- Theming a Webform with CSS and JS specific to this form
Theming elements via the Webform UI
The Webform UI allows a great amount of flexibility when you want to add custom classes to your form.
The wrapper and field classes added in the UI are the rendered in the html output
Theming elements via custom templates
If your theming needs are a bit more complex, theming your webform via custom tpl files is may be just what you need.
As a first step, enable theme_debug in settings.php. Do this by uncommenting the line for theme debug.
$conf['theme_debug'] = TRUE;
Theme Debug enables you to see information about what templates are responsible for rendering markup on a page, as well as showing template suggestions if you wish to override a template.
You’ll see that theme debug shows that the webform output is being generated by path-to-contrib-modules/templates/webform-form.tpl.php in the webform module.
Copy this file and place in your current theme and rename based on template suggestions for webform.
- So if your webform node ID is 1, you would name the file webform-form-1.tpl.php
Within the webform-form-1.tpl.php file, form fields are rendered via this line:
If you’re using devel, you can easily view the fields on the form by adding the following to your tpl file:
You can the render any of the fields in the webform in any order that you want, and group them with markup as you need. Here, I’ve added a div with the class of jumbotron and wrapped the First Name and Last Name fields. I’ve also added some divs to add a grid layout to some of the other form elements.
Once you render a form element individually, it will not render within the $form[‘submitted’] render array anymore.
Here’s the rendered result of the tpl changes just made.
Altering a Webform with hook_form_alter()
You can also theme your form using hook_form_alter().
See Programmatically modifying a webform with hook_form_alter() | Drupal.org
Add a hook to your theme or custom module.
We’re going to alter the markup for some of the fields in our form.
Anything you can do using Drupal’s FAPI (Form API) can be done here.
Theming a Webform with CSS and JS specific to this form
As an exercise, we’re going to display an icon when the selected option changes for Reason for Contact.
The JS File
The CSS file
And here’s the result!
With these tools in hand, you can theme any of your webforms any way you want. Happy theming.