Drupal form theming

After creating a custom form with FAPI (Drupal's Form API), it can be hard to theme it just like you want. Here's how to do some basic form theming including the creation of a template (.tpl.php) for the form. Note that the theme hook name must be the same as the form name.

In mymodule.module:

<?php
 
/**
 * Example form.
 */
function mymodule_my_form() {
  $form = array();
  $form['examplefield'] = array(
    '#value' => t('Example field.'),
    '#type' => 'markup',
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Go'
  );
  return $form;
}
 
/**
 * Implements hook_theme().
 */
function mymodule_theme($existing, $type, $theme, $path){
  $hooks = array();
  $hooks['mymodule_my_form'] = array(
    'template' => 'mymodule-my-form',
    'render element' => 'form',
  );
  return $hooks;
}
 
/**
 * Preprocess My Form
 */
function template_preprocess_mymodule_my_form(&$variables){
  $variables['my_variable'] = 'My Variable';
}
?>

create mymodule-my-form.tpl.php in module folder

<div id="example-my-form-wrapper">
  <?php print render($form['my_element1']); // print out a form element ?>
  <?php print render($form['my_element2']); // print out another form element ?>
  <?php hide($form['my_element3']); // don't show this element so we can display it last ?>
  <?php print drupal_render_children($form); // print the remaining form elements except for the hidden one ?>
  <?php print render($form['my_element3']); // print out the hidden form element ?>
</div>
Now, to get the fully rendered form, do:
<?php
render(drupal_get_form('mymodule_my_form'));
?>

Tags

Internal References

Article Type

General