Add a #legend property to certain composite form elements

Created on 30 April 2017, over 7 years ago
Updated 21 March 2023, over 1 year ago

Problem/Motivation

I had an idea for certain Form API elements (i.e., anything using CompositeFormElementTrait) a while ago. I implemented it in the Lightning distribution a while ago, with the intention of cross-porting it to core. Well, I'm bored on a train and I figured I'd do the cross-port now.

The idea is to implement a #legend property for (primarily) checkboxes and radio buttons. This property would provide a convenient way to set descriptive text on the individual option elements. Normally you'd have to do this with a custom #process or #after_build callback, or similar. This could be potentially useful if presenting the user with several options that would benefit from deeper explanation, without needing to stuff all of that explanatory text into the description area for the composite element.

When building a form, it would be used like so:

$form['fruit'] = [
  '#type' => 'radios',
  '#title' => t('Choose your favorite fruit'),
  '#options' => [
    'apple' => t('Apple'),
    'orange' => t('Orange'),
    'banana' => t('Banana'),
    'blueberry' => t('Blueberry'),
  ],
  '#default_value' => 'blueberry',
  '#legend' => [
    'apple' => t('A genetically varied fruit found in temperate climate zones and elsewhere.'),
    'orange' => t('A delicious citrus with which nothing rhymes.'),
    'banana' => t('Slightly radioactive, but high in potassium.'),
    'blueberry' => t('Basically the best damn thing ever.'),
  ],
];

(It's pretty clear where my biases lie. :)

The result of this code would be that the final rendered element would be a set of radio buttons, and directly below the Apple radio we'd have the text "A genetically varied fruit found in temperate climate zones and elsewhere," and so forth for each option.

For a little more power, the legend can also be a callable that is called for each option, receiving four parameters -- the option, the full element, the form state, and the complete form. It would be expected to return a descriptive string for the option.

API Changes

Certain form elements would now support an entirely optional #legend property.

Data Changes

Zilch.

UI Changes

None.

Remaining Tasks

Get buy-in, write tests, commit, and document.

Feature request
Status

Needs work

Version

10.1

Component
Form 

Last updated 6 days ago

Created by

🇺🇸United States phenaproxima Massachusetts

Live updates comments and jobs are added and updated live.
  • Needs tests

    The change is currently missing an automated test that fails when run with the original code, and succeeds when the bug has been fixed.

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.

Production build 0.71.5 2024