How to theme a Drupal form using tpl.php file

You may already know that tpl.php files are the template controls wich can only affect the output of the contents. This comes to play because of the great power of PHPTemplate template engine. PHPTemplate is a theme engine written by Adrian Rossouw (who was also behind the theme reforms in Drupal 4.5).

It uses individual something.tpl.php files to theme Drupal's theme_something() functions. Drupal'sthemeable functions are documented on the Drupal API site. Every file contains an HTML skeleton with some simple PHP statements for the dynamic data. Thus, PHPTemplate is an excellent choice for theming if you know a bit of PHP: with some basic PHP snippets, you can create advanced themes easily.

If you don't know PHP, then PHPTemplate can still be a good choice because only small bits of code are involved. They can just be copy/pasted into your template.

Here I'm going to discuss about how to theme a form in your module, just in few lines.

1. Create the Drupal form.

<?php
/**
* Drupal form you can use any type of element here
*/
function MODULE_NAME_form(&$form_state) {
  $form = array();
  $form['search'] = array(
    '#type' => 'textfield',
    '#title' => t('Search here'),
  );
  $form['search_button'] = array(
    '#type' => 'submit',
    '#size' => 10,
    '#value' => t('Search'),
  );
  return $form;
}
?>

2. Go to your template.php file in your theme folder and use below to register your theme.

<?php
function THEMEM_NAME_theme() {
  return array(
    'MODULE_NAME_form' => array(
      'arguments' => array('form' => NULL),
      'template' => NAME_OF_THE_TPL_FILE,
      'path' => PATH_TO_TPL_FOLDER,
    ),
  );
}
?>

3. Adding the preprocess to manage Form elements as variables. (Add this to same template.php file)

<?php
/**
* Adding download page prepoces funton
*/
function THEME_NAME_preprocess_MODULE_NAME_form(&$vars, $hook) {
  $vars['search'] = drupal_render($vars['form']['search']);
  $vars['search_button'] = drupal_render($vars['form']['search_button']);
  // this is must
  $vars['form_extras'] = drupal_render($vars['form']);
}
?>

4. Create the tp.php files in your theme folder

// Search textfield
<?php echo $search; ?>
// Search button
<?php echo $search_button; ?>
// this is must
<?php print $form_extras; ?>