Labels do not have correct 'for' attribute if 'id' set in #attributes

Created on 15 June 2021, over 3 years ago
Updated 21 January 2023, almost 2 years ago

Problem/Motivation

If a form element ID is explicitly assigned with the #id property, the associated label's for property will correctly reference that id.

If a form element ID is explicitly assigned via the 'id' property in #attributes, the id is correctly assigned, but the label's for attribute references does not reference that id, instead using what the ID would have been had the ID been automatically generated.

Steps to reproduce

1. Add the search block to the page
2. Add a preprocess form alter hook to the .theme file, and set the form ID

function SUBTHEME_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  // This is for Drupal core search block.
  if ($form_id == 'search_block_form') {
    $form['keys']['#attributes']['id'][] = 'cd-search';
  }
}

3. Clear cache and reload page. Notice the form label's ID does not reference the form ID but instead defaults to for="edit-keys"

Proposed resolution

Have id and for match for accessibility reasons.

Before

After

Remaining tasks



User interface changes

None

API changes

None

Data model changes

None

Release notes snippet

Fixes form inputs where the element ID is explicitly assigned with the #id property, the associated label's for property will correctly reference that id.

πŸ› Bug report
Status

Needs work

Version

10.1 ✨

Component
FormΒ  β†’

Last updated 1 day ago

Created by

πŸ‡ΊπŸ‡ΈUnited States bnjmnm Ann Arbor, MI

Live updates comments and jobs are added and updated live.
  • Accessibility

    It affects the ability of people with disabilities or special needs (such as blindness or color-blindness) to use Drupal.

Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

  • Status changed to Needs work almost 2 years ago
Production build 0.71.5 2024