How to create a custom template file for a form with Zen subthemes

There are two stages of understanding needed in order to create a template file for a form in a Zen subtheme. The first level in my opinion is to understand how to achieve that same result in a normal theme.

In a normal theme all we need to know in order to create a working tpl (template file) for a form is the form id in question and the format to connect that form to the tpl from within the template.php file.

For the sake of this example I am going to show how to theme the user registration form in Drupal, which has a form id of “user_register”. The code below would be entered in to your template.php file. Please note that this is how to achieve the result for a normal theme. I will show you how to do the same thing for a Zen subtheme in a moment.

function example_theme() {
  return array(
    ‘user_register’ => array(
      ‘arguments’ => array(‘form’ => NULL),
      ‘template’ => ‘user-register’,
    ),
  );
}

Now when you start on a Zen subtheme the format is slightly different, and the documentation is incomplete, so I am going to show you how to do it with the code below.

function example_theme(&$existing, $type, $theme, $path) {
  $hooks = zen_theme($existing, $type, $theme, $path);
  // The code below adds a tpl for the user registration page
  $hooks[‘user_register’] = array(
    ‘arguments’ => array(‘form’ => NULL),
    ‘template’ => ‘user-register’,
  );
}

Obviously you would switch out the word example with your theme name.

What this code accomplishes is that it allows you to create file in your theme called user-register.tpl.php which will have full access to the form and which will allow you to tinker with the html and the ordering of the fields to your hearts content.

I will go into how to advanced form theming in a separate tutorial, but for now I will just give you the essential idea of what goes into the user-register.tpl.php with the code below.

Now obviously the code above wouldn’t alter the form at all, but if you use the devel module and run a dvm() on the $form variable you will see all of the form elements which can be extracted and rendered separately.

One very important thing to keep in mind is that no matter what you do with the individual fields you should always print drupal_render($form) at the end of the tpl to insure that all hidden form fields are created. Not doing so can cause forms to break or to behave strangely.

Another point worth mentioning is that for some forms there is javascript associated with form validation which is dependent on the normal hierarchy of the DOM (Document Object Model). In layman terms this means that if you go too crazy with the html surrounding some form fields some javascript might not work, in which case you either adjust your html, or you roll your own javascript.

Good luck.