Same name and namespace in other branches
  1. 8.9.x core/includes/form.inc \template_preprocess_form_element_label()
  2. 9 core/includes/form.inc \template_preprocess_form_element_label()

Prepares variables for form label templates.

Form element labels include the #title and a #required marker. The label is associated with the element itself by the element #id. Labels may appear before or after elements, depending on form-element.html.twig and #title_display.

This function will not be called for elements with no labels, depending on #title_display. For elements that have an empty #title and are not required, this function will output no label (''). For required elements that have an empty #title, this will output the required marker alone within the label. The label will use the #id to associate the marker with the field that is required. That is especially important for screen reader users to know which field is required.

To associate the label with a different field, set the #for property to the ID of the desired field.

Parameters

array $variables: An associative array containing:

  • element: An associative array containing the properties of the element. Properties used: #required, #title, #id, #value, #description, #for.

File

core/includes/form.inc, line 535
Functions for form and batch generation and processing.

Code

function template_preprocess_form_element_label(&$variables) {
  $element = $variables['element'];

  // If title and required marker are both empty, output no label.
  if (isset($element['#title']) && $element['#title'] !== '') {
    $variables['title'] = [
      '#markup' => $element['#title'],
    ];
  }

  // Pass elements title_display to template.
  $variables['title_display'] = $element['#title_display'];

  // A #for property of a dedicated #type 'label' element as precedence.
  if (!empty($element['#for'])) {
    $variables['attributes']['for'] = $element['#for'];

    // A custom #id allows the referenced form input element to refer back to
    // the label element; e.g., in the 'aria-labelledby' attribute.
    if (!empty($element['#id'])) {
      $variables['attributes']['id'] = $element['#id'];
    }
  }
  elseif (!empty($element['#id'])) {
    $variables['attributes']['for'] = $element['#id'];
  }

  // Pass elements required to template.
  $variables['required'] = !empty($element['#required']) ? $element['#required'] : NULL;
}