Optgroups on select attribute are not supported

Created on 6 September 2025, about 2 months ago

Problem/Motivation

I would like to use optgroups on select element. However, due to the current implementation only flat list of options is supported. Attempt to provide an optgroup results in error.

Steps to reproduce

Create a link attribute of type select and add options with optgroups:

attribute:
  type: select
  title: Select with optgroups
  options:
     Group1:
        key1: Value1
     Group2:
        key2: Value2

Proposed resolution

Currently it fails due to the option translation in /src/LinkAttributesManager.php that only handles a single level of options:

    // Translate options.
    if (!empty($definition['options'])) {
      foreach ($definition['options'] as $property => $option) {
        $definition['options'][$property] = new TranslatableMarkup($option);
      }
    }

Proposal is to allow handling inner arrays, also translating $property when $option is value, e.g.:

    // Translate options.
    if (!empty($definition['options'])) {
      $definition['options'] = $this->translateOptions($definition['options']);
    }
  }

  /**
   * Translate options, preserving optgroups.
   *
   * @param array<string,mixed> $options
   *   Array of options, possibly grouped.
   *
   * @return array<string,mixed>
   *   Array with optgroups and option values translated.
   */
  private function translateOptions(array $options): array {
    $translated = [];
    foreach ($options as $property => $option) {
      if (is_array($option)) {
        $translated[(string) new TranslatableMarkup($property)] = $this->translateOptions($option);
      }
      else {
        $translated[$property] = new TranslatableMarkup($option);
      }
    }
    return $translated;
  }

Remaining tasks

-

User interface changes

-

API changes

-

Data model changes

-

🐛 Bug report
Status

Active

Version

2.1

Component

Code

Created by

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Production build 0.71.5 2024