2 min read

Drupal 7: Defining templates for forms and form theming

How to define custom templates and use them to build content was discussed in the article Drupal 7: Defining template files tpl.php and theming hooks. A common task is custom theming of forms. Drupal provides a great mechanism for this through the use of *.tpl.php templates.

A template for a form is defined very simply:

/**
 * Implements hook_theme().
 */
function MYMODULE_theme() {
  return array(
    'login_form' => array( // form id
      'render element' => 'form', // specifies that the element to render is a form
      'template' => 'custom_form_template', // template name: custom_form_template.tpl.php
    ),
  );
}

The key in the array is the form ID, which can be found using Firebug, the Devel module functions, or by the name of the function defining the form.

Now, in your template, you can output the form contents individually:

<div class="wrapper">
  <div class="left">
    <?php print render($form['login']); ?>
  </div>
  <div class="right">
    <?php print render($form['password']); ?>
  </div>
  <?php print drupal_render_children($form); ?>
</div>

To display an individual element, use the render function and pass it the array containing that specific element. It is also mandatory to use drupal_render_children($form) in the template to display any form elements not rendered individually.