3

I want to alter the HTML structure for a particular form in my site. Specifically, I want to add some wrapper DIVs around a few sets of form elements. What's the "Drupal 7" way of doing this?

3

You can implement hook_element_info_alter() to change the theme wrappers used by the form fields.

If you look at the code of system_element_info(), you will notice the form fields are defined as in the following code.

  $types['textfield'] = array(
    '#input' => TRUE, 
    '#size' => 60, 
    '#maxlength' => 128, 
    '#autocomplete_path' => FALSE, 
    '#process' => array('ajax_process_form'), 
    '#theme' => 'textfield', 
    '#theme_wrappers' => array('form_element'),
  );
  $types['machine_name'] = array(
    '#input' => TRUE, 
    '#default_value' => NULL, 
    '#required' => TRUE, 
    '#maxlength' => 64, 
    '#size' => 60, 
    '#autocomplete_path' => FALSE, 
    '#process' => array('form_process_machine_name', 'ajax_process_form'), 
    '#element_validate' => array('form_validate_machine_name'), 
    '#theme' => 'textfield', 
    '#theme_wrappers' => array('form_element'),
  );
  $types['password'] = array(
    '#input' => TRUE, 
    '#size' => 60, 
    '#maxlength' => 128, 
    '#process' => array('ajax_process_form'), 
    '#theme' => 'password', 
    '#theme_wrappers' => array('form_element'),
  );

You can add a new form wrapper, or change the existing one. Suppose, for example, that you want to add a theme wrapper for the textfield form field; you could use code similar to the following one.

function mymodule_element_info_alter(&$type) {
  if (isset($type['textfield'])) {
    $type['textfield']['#theme_wrappers'] = array_unshift($type['textfield']['#theme_wrappers'], 'mymodule_textfield_wrapper');
  }
}

Your module then should implement the theme_mymodule_textfield_wrapper() theme function, and hook_theme() to declare it. You can use the code of theme_form_element() as guideline to write your code. The form element is contained in $variables['element'].

Alternatively, if the form fields you want to wrap with additional HTML use all the same theme wrapper, you can override that theme function using hook_theme_registry_alter(). Be careful, as in this case you are also altering every form field using that theme wrapper, including future form fields for which your wrapper could cause issues.

  • I guess the logical follow up question to this is: how do you add your own custom theme wrapper? – Lester Peabody Jul 25 '12 at 20:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.