Drupal theming form elements

Theming form elements in Drupal can be a pain. Here's how I do it.

<?php
## assign #theme_wrapper on form element

function MYMODULE_super_special_form($form, &$form_state) {
// ...
$form['super_special_checkbox'] = array(
    '#type' => 'checkbox',
    // the #title is the label field so don't include it here if you plan on having the 
    //  <label> inside the <input>. Instead, create a form template and print render
    //  this element inside of a <label>Title</label> there
    //'#title' => t('Super'),
    '#required' => FALSE,
    '#default_value' => $recommended,
    '#theme_wrappers' => array('MYMODULE_super_special_form_element'),
  );
// ...
}
 
## implement hook_theme:

MYMODULE_theme(){
  return array( 
    //notice that there is no  theme_  prefix
    'MYMODULE_super_special_form_element' => array(
      'render element' => 'element',
    ),
  );
}
 
## then copy theme_form_element() from includes/form.inc and alter to suit:

// notice the  theme_MYMODULE  prefix here
function theme_MYMODULE_super_special_form_element($variables) {
  $output = $variables['element']['#children'] . "\n";
  return $output;
}
?>

Tags

Internal References

Article Type

General