Skip to main content

Theme Drupal Form

Theme Drupal Form

In this example, we are theming Drupal form different from its
default layout. Suppose we have a search form with two fields search
textbox and category selectbox. We are assuming that our module name is “search“.

Default Layout Search Form

Default Layout Search Form

Themed Layout Search Form

Themed Layout Search Form

Step 1. Create search form using Drupal Form API.

function search_form() {
	$form['str'] = array(
	'#type' => 'textfield',
	'#size' => '32',
	);
 
	$form['category'] = array(
	'#name' => t('category'),
	'#type' => 'select',
	'#options' => array('0' => t('All'), '1' => t('Bars'), '2' => t('Restaurants')),
	);
 
	$form['submit'] = array(
	'#type' => 'submit',
	'#value' => t('Search'),
	);
 
	return $form;
}

Step 2. Register our theme in Drupal theme registry using hook_theme().

function search_theme() {
 global $theme;
 
 return array(
  'search_form' => array(
   'arguments' => array('form' => NULL, 'theme' => $theme),
   'template' => 'search-form',
  ),
 );
}

Step 3. Create search-form.tpl.php file to theme this search form.

<table cellspacing="0">
	<tr>
  	<td class="container-inline"><strong><?php print t('Search');?></strong> <?php print drupal_render($form['str']); ?></td>
    <td class="container-inline"><strong><?php print t('Category');?></strong> <?php print drupal_render($form['category']); ?></td>
    <td><?php print drupal_render($form['submit']); ?></td>
  </tr>
</table>
<?php
print drupal_render($form);
?>

,