Drupal: Use custom template file for any form


Introduction

Drupal 7 has well known template file concept. Template (.tpl) file is used to display the data and has minimal or no logic at all. I am pretty sure there are many scenarios where you would like to use your own template file. Most of the cases you can easily create template file using well documented instructions. For example, if you want to create template file for content type ‘Article’, you simply create a template file ‘node–article.tpl.php’ and put it inside your theme’s template folder. Drupal will automatically detects that template file and use it instead of default node.tpl.php. Similarly you can see theme suggestion of views just clicking on advanced->theme. But there are certain scenario where there is straight way to create and utilize template file. For example, you may want to customize login screen of your site and want to change layout or add more classes or add new div wrapper. To make use of template file in such scenario, we need to implement certain hooks.

Steps

First you need to add YOURTHEME_theme hook function in you theme->template.php file.

/**
 * theme_theme hook
 * @return type
 */
function MYTHEME_theme() {
    return array(
        'user_login' => array(
            'render element' => 'form',
            'path' => DIRECTORY_PATH_WHERE_YOU_WANT_TEMPLATE_FILE,
            'template' => 'user-login',
            'preprocess functions' => array('MY_FORM_PREPROCESS'),
        ),
    );
}

Now, if you want to update form data or add your own logic, you can use your preprocess function. Moreover, you can define your own custom variables which will be available to use in your template file. In the example below, I am creating new variable ‘myvariable’ which I can use in my template file later.

function MY_FORM_PREPROCESS(&$vars) {
    // Here you can have your own logic and 
    // you can define your own variables 
    // which will be available for you in your tpl file
    $vars['myvariable']='COMPLEX ARRAY';
}

Final step is to create tpl file in the directory you specified earlier. In this example, we have template name ‘user-login’. So, file name will be ‘user-login.tpl.php’. If you forget creating tpl file or misname it, drupal will fall back to use default way.

Further Question

Please leave your comment/question, if you have any concern implementing template file this way.

Advertisements