function FormPreprocess::preprocessFormElementLabel

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/lib/Drupal/Core/Form/FormPreprocess.php, line 178

Class

FormPreprocess
Initial preprocess callbacks for the form system.

Namespace

Drupal\Core\Form

Code

public function preprocessFormElementLabel(array &$variables) : void {
  $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;
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.