Problem/Motivation
According to the HTML specification when using the "label" element the "for" attribute should only be used when the element you're labelling is "labelable". See: http://www.w3.org/html/wg/drafts/html/master/forms.html#the-label-element
Labelable elements are:
button
input (if the type attribute is not in the Hidden state)
keygen
meter
output
progress
select
textarea
form-associated custom elements
Steps to reproduce
- Install Drupal with the Standard profile.
- Visit
/admin/config/media/file-system. - Inspect the markup for "Public file base URL",
In addition to inspecting the markup, note the pointer as you hover over the text in Step 3.
Proposed resolution
- Add the property
non_labelableto theItemelement (Drupal\Core\Render\Element\Item). - Add the variable
tagto all versions ofform-element-label.html.twig. - In
core/lib/Drupal/Core/Form/FormPreprocess.php, set that variable tolabelif the form element is labelable (and keep the existing markup). If not, then settagtospan, add anidattribute to it, and add anaria-describedbyattribute to the wrapping<div>. (Since (1) applies only toItemelements, that is the only non-labelable form element.)
In future issues, we may add the non_labelable property to other form elements. In (3), the code just checks for the property, not the element type.
Remaining tasks
User interface changes
Here is the markup for the "Public file base URL" section: see the Steps to Reproduce. Both code snippets below use the Default Admin theme.
Before
<div data-drupal-wrapper-selector="edit-file-public-path" id="edit-file-public-path" class="js-form-item form-item js-form-type-item form-type--item js-form-item-file-public-path form-item--file-public-path">
<label for="edit-file-public-path" class="form-item__label">Public file system path</label>
sites/default/files
<div id="edit-file-public-path--description" class="form-item__description">
A local file system path where public files will be stored. This directory must exist and be writable by Drupal. This directory must be relative to the Drupal installation directory and be accessible over the web. This must be changed in settings.php
</div>
</div>
The <label> element has a for attribute referring to the wrapping <div>.
After
<div data-drupal-wrapper-selector="edit-file-public-path" id="edit-file-public-path" aria-describedby="edit-file-public-path--label" class="js-form-item form-item js-form-type-item form-type--item js-form-item-file-public-path form-item--file-public-path">
<span id="edit-file-public-path--label" class="form-item__label">Public file system path</span>
sites/default/files
<div id="edit-file-public-path--description" class="form-item__description">
A local file system path where public files will be stored. This directory must exist and be writable by Drupal. This directory must be relative to the Drupal installation directory and be accessible over the web. This must be changed in settings.php
</div>
</div>
The <label> element is replaced by a <span> element with an id attribute. The wrapping <div> refers to that element using aria-describedby.
Introduced terminology
None
API changes
None
Data model changes
None
Release notes snippet
N/A
Original report by specky_rum
According to the HTML specification when using the "label" element the "for" attribute should only be used when the element you're labelling is "labelable". See: http://www.w3.org/html/wg/drafts/html/master/forms.html#the-label-element
Labelable elements are:
button
input (if the type attribute is not in the Hidden state)
keygen
meter
output
progress
select
textarea
Currently the theme_form_element_label($variables) function takes no account of the type of the element it is labelling. As long as there's an ID for the element it adds this as the "for" attribute. This is done where it does this:
if (!empty($element['#id'])) {
$attributes['for'] = $element['#id'];
}
The "for" attribute is not a required attribute so presumably we could just add an array of element names or Drupal form element types in this function to exclude the "for" attribute?
The reason this has come up is that a site we manage failed an accessibility check run by the Shaw Trust in the UK. The issue they raised was that there are labels without a corresponding element. In fact, they do have an element, it's just that it's a div. The specific example is a form created using the entityform module which includes a list of checkboxes. Now although that's a contrib module it uses the standard Drupal core field rendering code. An example of the resultant code for checkboxes is something like:
<div class="form-item form-type-checkboxes form-item-field-a3-posters-location-und">
<label for="edit-field-a3-posters-location-und">Location </label>
<div id="edit-field-a3-posters-location-und" class="form-checkboxes"><div class="form-item form-type-checkbox form-item-field-a3-posters-location-und-Adam-and-Eve-Street-car-park">
<input id="edit-field-a3-posters-location-und-adam-and-eve-street-car-park" name="field_a3_posters_location[und][Adam and Eve Street car park]" value="Adam and Eve Street car park" class="form-checkbox" type="checkbox"> <label class="option" for="edit-field-a3-posters-location-und-adam-and-eve-street-car-park">Adam and Eve Street car park (2 sides; behind Grafton centre) </label>
</div>The only problem with that code is that the label's "for" attribute refers to the id of a div which is not a "labelable" element.
We have got round this for the very specific instance of checkboxes by implementing theme_form_element_label($variables) in our theme but this is a very specific override and not appropriate to core. Our full override function is as follows (it will be extended to pick up other element types in future):
function theme_form_element_label($variables) {
// run the regular theme function on it
$output = theme_form_element_label($variables);
// check if it's checkboxes
if ($variables['element']['#type'] == 'checkboxes') {
// if it is, strip out the "for" attribute
$output = preg_replace('#\s(for)="[^"]+"#', '', $output);
}
return $output;
}
| Comment | File | Size | Author |
|---|---|---|---|
| #43 | 2279111-alexpott-review-interdiff.txt | 12.01 KB | mgifford |
| #30 | drupal-2279111.zip | 9.49 KB | mgifford |
| #18 | 2279111-18.patch | 1.96 KB | lauriii |
Issue fork drupal-2279111
Show commands
Start within a Git clone of the project using the version control instructions.
Or, if you do not have SSH keys set up on git.drupalcode.org:
Comments
Comment #1
dcam commentedWork has been done in 8.x to correct this problem. Groups of radios and checkboxes now have a legend instead of a label. Work is on-going to continue improving these elements. See the related issue. Unfortunately, this can't be fixed in core for 7.x because the change would break every theme. There may be a contributed module that will override the theming to make it accessible. I'm closing this issue as a duplicate.
Comment #2
David_Rothstein commentedI think this might still be relevant actually. Even if Drupal 8 fixed it for checkboxes and radios, is it still a problem for other elements?
We can't switch label to legend in Drupal 7 certainly, but simply leaving out the "for" attribute in these cases seems like it would be doable as a backport. However, would that really help accessibility - i.e. is pointing screen readers nowhere better than pointing them to a div? Seems like it might actually be worse...
Personally I've also come across this issue during automated accessibility scans of particular sites, but note #884846-39: Orphaned Labels Being Generated for Radios, Checkboxes & Items which suggests that this issue has "no real impact on users, only on testing tools". I used that as a justification not to bother fixing it on the site in question :)
Comment #3
mgiffordPerhaps. I'm not sure what other elements though. Certainly every
<label>should be associated with an<input>type with aforattribute. It was an issue for multipart forms like radios & checkboxes.Hadn't heard of the http://www.shaw-trust.org.uk folks before...
Drupal 7 uses
<label>incorrectly in form elements as you would a header. #2249089: Improper use of a LABEL for Last Saved & Author & #2250015: Improper use of a LABEL for user profile are some examples where we've fixed this in D8.@David_Rothstein you asked "is pointing screen readers nowhere better than pointing them to a div? Seems like it might actually be worse..."
Removing the
forwould be not pointing them anywhere vs pointing them to adiv. The point would be to remove the pointer.I'm really not sure what elements are legitimately using labels, are available in Drupal Core, and aren't already covered. We are still waiting on a solution for #2192419: Use a WCAG-compliant fieldset (fieldgroup) for #type radios/checkboxes but I don't think that expanding theme_form_element_label($variables) function will help.
Non-labelable elements should not use a
label, but rather should use adiv.Comment #4
dawehnerThis fits better into the form subsystem
Comment #11
katannshaw commented@specky_rum: I see that this is an old post but I thought I'd offer my thoughts on the subject. I think there are two ways to deal with this issue. I see the Forms API dealing with this properly on the Admin > Configuration > Text formats > Basic HTML page under "Enabled filters" when you inspect the code. Here's a code snippet:
As you can see, the id of the wrapping
<div>element matches the<label>element's "for" attribute, and then the inner<input>and<label>elements have matching id/for values.The other way to deal with it is to place it into a
<fieldset>element which would be a more proper way to do things. The Contact Form module does this, and it would be great of the Forms API would as well in the future if it doesn't already. See more info at https://developer.mozilla.org/en-US/docs/Web/HTML/Element/fieldset-Kat
Comment #16
amber himes matzIt looks like from #11, that Form API is handling this situation correctly, and best practice methods were suggested as well.
I think this can be closed as works as designed.
Comment #17
klonos@katannshaw and @Amber Himes Matz admittedly this is a hard problem to fix, but at the same time I don't think that it can be marked as "works as designed".
To sum up the problem:
<label>elements should have aforattribute that points to an HTMLidof a labelable element (see https://html.spec.whatwg.org/multipage/forms.html#the-label-element )<div>elements are NOT labelable elements (see https://html.spec.whatwg.org/multipage/forms.html#category-label ), so they should not be pointed to via theforattribute (and not have a<label>to begin with).So this for example, is NOT proper use of the label and for attribute:
After some quick research, the best suggestion I have found is to use a combination of a
<span>and thearia-describedbyattribute. Something like this for instance:Noting the following from https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attribut... :
aria-labelledbyattribute is not appropriate, because it should only be used for interactive elements (whichdivs are NOT)aria-describedbyis not ideal either, since it should be used for a description (longer text) rather than a label (short text)Reopening this issue in order to figure out a proper solution to this, rather than haste to dismiss it.
Comment #18
lauriiiThis isn't implementing exactly what is in #17 which I think would be ideal. However, based on #3, it might be an improvement to remove the
forattribute when the label is not used for phrasing content. Here's a patch that tries to add support for that in Form API, and adds a use of this to\Drupal\Core\Render\Element\Item.Comment #19
smustgrave commentedShould a follow up be made for the other points from #17. Think since this adds improvement it should still move forward. Could the issue summary be updated and tests added?
Comment #21
benjifisherI am removing the "Needs backport to D7" issue tag, since it is obsolete. I am not sure about the "label" tag. There are 35 other issues that have it, so maybe it is useful.
I agree with Comment #19, at least the part about needing test coverage. I am adding the tag for that.
I am pretty sure that #3082011: Do not use label HTML tag in "item" form element is a duplicate of this issue, and I prefer the approach here in Comment #18. If at least one person agrees with my opinion, then let's close the other issue.
I prefer the approach in Comment #18 to that in Comment #17. I think that a
<label>element has more semantic meaning than a<span>, and we do not have to do extra work to style it. But I will defer to a11y experts and front-end developers.I am adding #3490435: [regression] Form #states are processed and can be added to the wrong attribute for 'item' elements as a related issue. Maybe it is a stretch to do that, but both issues involve special handling for the
itemrender element. Maybe the fix for one can inform the approach for the other.Edit: from Comment #3,
I defer to mgifford: unless standards have changed since that comment, or mgifford has some other reason to reconsider, I guess I am wrong about using
<label>. See also the comments from andrewmacpherson on #3082011: Do not use label HTML tag in "item" form element (Comments #2, #7).Comment #22
benjifisherI want to check that by fixing this issue we will not be regressing some previous issue.
I got some help from Claude code. It finds that the
idattribute on the wrapper div was added in #783438: #states doesn't work for #type item. Theforattribute in the label is newer: #1938926: Convert simpletest theme tables to table #type.The second issue was mostly about
<table>markup. I did not review the comments, but I searched for "item" and did not find any reference to theitemrender element. It seems likely that it was not considered on that issue.Based on that, I am reasonably confident that we can fix this issue without causing regressions.
Comment #24
benjifisherI opened a MR. I used Claude Code, but I gave it a lot of direction and made several manual edits.
I tested manually. On the page
/admin/config/media/file-system, I now see the markupI think that implements the recommendation from Comment #17.
The last commit updates the
idattribute on the wrapper: it removes the "edit-" prefix and adds "-wrapper". The same commit adds thearia-describedbyattribute and a matchingidattribute on the span.The last commit also updates the tests, but the changing
idattributes mean that the test-only CI job will not be meaningful. The first two commits add test coverage, and checking out those changes is a better way to test without any code changes.The commit
dfa506dfe31(Test #nonlabelable attribute, not #markup attribute) is arguably out of scope for this issue. It updates an existing check, intended for item elements, to use the new attribute. It may fix the related issue #3490435: [regression] Form #states are processed and can be added to the wrong attribute for 'item' elements.I am leaving the status at NW because of static analysis errors. I will get to that later. I may add "labelable" to the Cspell dictionary.
Comment #25
benjifisherI added "labelable" to the dictionary and changed "nonlabelable" to "non_labelable".
Should I have used
drupal-dictionary.txtinstead ofdictionary.txt?Comment #27
mgiffordSo after looking at https://www.drupal.org/project/drupal/issues/3082011 I thought there were elements of @intrafusion's which should be pulled into this.
This consolidation adds on top https://git.drupalcode.org/project/drupal/-/merge_requests/16464/diffs
1. Explicit `#non_labelable` metadata for wrappers like `#type => item`.
2. Programmatic association for non-labelable wrappers via:
- wrapper: `id="-wrapper"` + `aria-describedby="-label"`
- title: `-label">...` (or custom `#title_tag`)
3. Regression coverage proving the relationship (no invalid `label[for]` targeting `div`, no orphan title text).
Credit first: this approach builds directly on intrafusion's re-roll in #3082011 comment #16669292 (`3082011-22.patch`). Thank you, @intrafusion, for pushing the `#title_tag` + template simplification pattern forward.
#### 1. W3C / HTML spec compliance
Per HTML spec, `label[for]` is for labelable controls only (`input`, `select`, `textarea`, `button`, etc.). Pointing `for` at a `div` fails validation and creates noisy false positives in scanners.
#### 2. Accessible association via ARIA
Removing invalid `for` references is necessary, but not sufficient. We still need a programmatic relationship between wrapper and title for assistive tech.
This patch path does that by:
- marking elements as non-labelable (`#non_labelable => TRUE`),
- rendering wrapper ids as `-wrapper`,
- rendering title ids as `-label`,
- wiring wrapper `aria-describedby` to the title id.
So we get valid HTML and preserved accessibility semantics.
This is an AI generated consolidation, but made sense to me.
Comment #28
benjifisher@mgifford:
I left several suggestions on MR !16464. I am setting the status back to NW.
I think the main changes relative to MR !16441 are
idattribute on the wrapper div fromedit-...to...-wrapper. I already suggested, in a comment on MR !16441, that such a change might be a bad idea.tagvariable to the Twig template in addition tonon_labelable. (One of my suggestions is to pass it instead of, not in addition to.)--labelinstead of-label.Testing MR !16464, I see the following markup on
/admin/config/media/file-system:The only differences compared to the snippet in Comment #24 are the result of (1) and (3).
Comment #29
benjifisherWe need to update the issue summary with the standard template and provide at least the proposed resolution. I do not have time to do that now, but I will add the issue tag.
Both MRs have test coverage, so I am removing the tag for that.
This issue will also need a change record, so another issue tag.
Although I do not have time to rewrite it, I did review the current issue summary. It lists the labelable elements, and the list in the current summary agrees with https://html.spec.whatwg.org/multipage/forms.html#category-label, except that the list here includes
keygen. In particular, Drupal'scheckboxeselement renders as a group of<input type="checkbox">elements, wrapped in a<div>. According to the issue summary, the label (if present) refers to the wrapping div. But that seems to be obsolete. Looking at the configuration form for a block (Go to/admin/structure/blockand follow the Configure link for any block) the "Response status" section has the markup (using the Claro theme)So we should review the markup for other form elements. Perhaps
itemis not the only one that needs to be updated.I thought perhaps that we could handle
itemthe same way ascheckboxes, but I think the<label>element is added in the preprocess function, so in fact we seem to be on the right track.Comment #30
mgiffordThis has been sitting here for a month, so this may not be a terrible time to see if this AI generated patch helps nudge things along.
The updated patch:
Reviewing the interdiff this seems to almost flip many of the assumptions, I think it makes it easier to understand the code.
Comment #31
benjifisher@mgifford:
Yes: a month ago I commented on your MR and on this issue, and you did not reply until yesterday.
If you want to move this issue along, then it would be more effective to update your MR and/or comment on this issue.
I would like to work with you to get this issue to a good place, but I am not sure how to do that. Usually, one person takes the developer role, working on a merge request, and a second person takes the reviewer role. I am happy to take either role.
Comment #32
mgifford@benjifisher 1st of all, sorry. I'm definitely still trying to wrap my head around how to work with this GitLab instance. Most of my commits have been historically done in Drupal with good old .patch files and maybe a few interdiffs.
I find the two interfaces quite confusing. I tossed up the .zip as I didn't want to mess up the MR.
Let me go take a look at your comments. I would rather not be the reviewer. I can work to see that the code "works" but I do limited day to day Drupal and haven't for a long while.
Comment #34
benjifisherI am updating the issue summary and removing the related issue tag. I think this issue still needs a change record.
I reviewed the code and did another round of manual testing. (I used the test results in the issue summary.) It all looks good to me, but I am leaving the status at NW because this issue still needs a change record.
Comment #37
benjifisherMR !16464 had modify/delete conflicts because the Claro theme was removed. I rebased and resolved the conflicts.
Comment #38
benjifisherComment #39
benjifisherI added a draft change record, and I am updating the snippets in the issue summary to use the Default Admin theme instead of Claro.
The issue status was NW for a change record (Comment #34). Although I updated the MR and resolved conflicts (Comment #37) I am still taking the reviewer role, so I can set the status to RTBC.
Comment #40
benjifisherI am changing the title to reflect the current scope of this issue: it affects only Form API elements with
'#type' => 'item'. (But see the last line of the Proposed resolution.)Comment #41
quietone commentedI read the comments, the MR (not a review) and the change record. The short version is that the core gates are passing. I have updated credit.
I prefer not to have words added to the dictionary but labelable is used on https://html.spec.whatwg.org/multipage/forms.html#the-label-element. Change records should start with the change instead of what happened 'previously'. But the change record is well written so no need to adjust it.
Leaving at RTBC
Comment #42
alexpottAdded some comments to the MR that need addressing.
Comment #43
mgiffordThank @alexpott I think I've addressed your points. I've added an interdiff. And yes, I've used AI.
Comment #45
benjifisherBack to NW: see my comments on the MR.
Comment #46
mgiffordSpellcheck didn't like "labelability". Some CSS changes and simplification of the PHP. All organized with AI with my supervision.
AI summarizes the changes like so:
<span>rather than<label>.Comment #48
benjifisher@mgifford:
I reviewed the current MR with help from Claude.
The biggest problem is that the
aria-describedbyattribute is not added. I mentioned this in one of the MR comments. Back to NW. Or maybe that is on purpose: in Comment #46, you listedas one of the changes. Is that what you meant? I thought a big part of this issue was to add the
aria-describedbyattribute.Thanks for catching the CSS rules targeting
.container-inline label. For testing purposes, I hacked `Drupal\system\Form\FileSystemForm`, adding some test form elements:Claude found some other places where
labelelements are targeted: see the MR comments and alsocore/misc/states.js, which toggles theform-requiredandjs-form-requiredclasses.There are cases where the preprocess functions no longer pass a
forattribute to the Twig template. This may be a problem for non-core themes that expect it. I am adding the issue tag for a change record.As long as I am thinking about issue tags, I am adding one for a follow-up issue. In Comment #40, I changed the title and narrowed the scope of this issue. We should either restore the full scope or handle additional form elements in a separate issue.