First Steps for Theming Forms
Find the Form ID
Before you can do anything, you’ll need to find the ID of the form you’re working with. It appears in the following two places in the markup of every form:
There’s a hidden field near the bottom of the form named form_id that contains what you’re looking for.
- <input type="hidden" name="form_id" value="exampleform_unsubscribe" />
Although it’s not copy/paste ready because it contains dashes instead of underscores to separate words, the
<form>'s ID attribute also contains the form ID.
- <form id="exampleform-unsubscribe">
Each Form ID has a corresponding function, which follows Drupal module naming conventions. In this example, exampleform is the module name and unsubscribe is what the form is named by the module.
Sometimes it helps to look at the original form and code comments when theming. You’ll often find the original function that generates the form in the
.module file of the module that created the form. If you find that the form doesn’t exist in the
.module file, it’s definitely inside the module somewhere, but you may have to look around. Sometimes developers use
.inc files for organization and code efficiency purposes.
In order to be able to use template files, preprocess, or process functions with forms, the first thing you’ll need to do is register the form ID as a theme hook. This is necessary so that Drupal knows about the theme hook. Drupal core does this for some forms in core, mostly for administrative forms that use tables, but chances are you’ll need to do this manually.
In your theme’s
template.php file, you’ll create an implementation of
hook_theme(), with your theme’s name in place of the hook prefix. As an example, you’ll theme the contact form located at
/contact when the Contact module is enabled, whose form ID is
contact_site_form. Inside you’ll specify the form ID as the key and the render element as form, as shown in Listing 16–27. The render element key is required for theme hooks that use the render API to generate markup, such as forms. Its value indicates the name of the variable that holds renderable element, which in this case is form.
After doing this and clearing the cache, you’ll be able to create a theme function and use preprocess and process functions for this form, which you’ll get into later in the chapter.