Drupal - How can I add a class to a label?

This post on StackOverflow says that the Drupal Form API does not support adding classes to labels, but it does contain a decent workaround:

Instead, you could target it using the wrapper class for the field and label:

.form-item-field-foo label {
  /* CSS here */
}

The API documentation for theme_form_element_label() shows why labels aren't possible (at least not out-of-the-box): the attributes array is initialized in the theme function and populated with just two optional classes ('option' and 'element-invisible').

So, is it completely impossible? In fact, I think it can be done, but I must add that I haven't tried this myself. You could try to:

  • Add a new #label_attributes property to some (or all) form elements using hook_element_info_alter() in a custom module;
  • Override theme_form_element_label() and make it merge the $attributes array with the value of $element['#label_attributes'].

If you're going to give this a try, please let us know if it worked.


You cannot set a class to the label tag of the form element using Form API's properties. However, you can set a prefix and a suffix to wrap the element (label + textarea) and use some nested CSS selector to accomplish what you are trying to do.

$form['name'] => array(
  '#type' => 'textfield',
  '#title' => 'Prénom'
  '#prefix' => '<div class="myClass">',
  '#suffix' => '</div>'
);

and in the CSS, you can select the label tag like this:

.myClass label {
  text-transform: uppercase; /* just for example */
}

Not a decent solution but that's how I usually do this, and have seen others do. #attributes is for the input element itself so it's correct your code adds the myClass class to the textarea.


On Drupal 8, do that simply by adding in your_module.module file

function your_module_preprocess_form_element(&$variables) {

  $element = $variables['element'];
  if (isset($element['#label_attributes'])) {
    $variables['label']['#attributes'] = array_merge(
      $variables['attributes'],
      $element['#label_attributes']
    );
  }
}

and add the #label_attributes on form creation :

$form['some_field'] = [
  [...]
  '#label_attributes' => [
    'some_attr' => 'some_value',
  ]
]

Tags:

Forms

7