Drupal - Change class on the div wrapper of a form element

You can override theme_form_element() normally if you want to change the theming globally. If you're interested in modifying just one specific form element then I'm aware of a couple of choices.

  1. You can register a new theme function for the particular type of form element you're interested in (eg. textfield). You then create this theme function (based on the original, eg. theme_textfield()) but that doesn't call theme('form_element', ...) at the end (you could either handle both the wrapper and the element in the one theme function, or you could make a separate wrapper theme function and use that). Finally you add a #theme property to a particular form element, and that element will get your custom theming.

  2. You can create a template file called form_element.tpl.php which just has the default behaviour of theme_form_element() and then use hook_preprocess_form_element() to add a template suggestion. Then you create the new template that matches the suggestion. You often hear people mentioning that templates are slightly slower than functions, and for such a frequently used theme call I can imagine people balking at using a template. I've never done any measurements for this myself however. Also, you need to have enough context at the preprocess stage to be able to make the suggestion.


I know this is a super old thread, but I'v been learning how to alter form elements and add classes. I got around to making a custom module:

function yourtheme_custom_form_alter(&$form, &$form_state, $form_id) {
 case'webform_number_whatever':
   _yourtheme_form_add_wrapper($form['submitted']['yourfieldhere'], array('form-field-some-style', 'not-label', 'whatever-other-styles-you-want'));
 break;
}

function _yourtheme_form_add_wrapper(&$element, $classes = array(), $type = array('form-item', 'form-type-textfield'), $removeTitle = FALSE){
  $element['#prefix'] = '<div class="' . implode(" ", $classes) . '"><div class="' . implode(" ", $type) . '">';
  $element['#suffix'] = '</div></div>';
}

To Change the "wrapper" you need to override form_element. Basically all form elements get rendered with the form_element theme theme_form_element($element,$value); (form.inc file)

So to change how this renders your form elements you simply copy that function to your template.php folder and rename it to: phptemplate_form_element($element,$value)

now you can make any changes and they will be used instead of the original function

  1. Copy theme_form_element($element,$value); from form.inc
  2. Paste it into (your theme) template.php
  3. rename it to: phptemplate_form_element($element,$value)
  4. clear all theme cache
  5. make whatever changes you want and they will be used.

Tags:

Forms

6