[2.0.0-rc3] EnumTrait::getEnumOptions()

Created on 29 January 2025, 1 day ago

Problem/Motivation

EnumPropType

      type: string
      enum: ["foo", "bar", "baz"]

Which is generating this form element (SelectWidget):

<select ...>
  <option value="" selected="selected">- None -</option>
  <option value="0">Foo</option>
  <option value="1">Bar</option>
  <option value="2">Baz</option>
</select>

But we want the enum value to be the submitted form value:

<select ...>
  <option value="" selected="selected">- None -</option>
  <option value="foo">Foo</option>
  <option value="bar">Bar</option>
  <option value="baz">Baz</option>
</select>

EnumListPropType

The same. i have this prop:

      type: array
      maxItems: 2
      items:
        type: string
        enum: ["foo", "bar", "baz"]

Whcih is generating this form element (SelectsWidget):

<select ...>
  <option value="" selected="selected">- None -</option>
  <option value="0">Foo</option>
  <option value="1">Bar</option>
  <option value="2">Baz</option>
</select>
<select ...>
  <option value="" selected="selected">- None -</option>
  <option value="0">Foo</option>
  <option value="1">Bar</option>
  <option value="2">Baz</option>
</select>

But we want the enum value to be the submitted form value:

<select ...>
  <option value="" selected="selected">- None -</option>
  <option value="foo">Foo</option>
  <option value="bar">Bar</option>
  <option value="baz">Baz</option>
</select>
<select ...>
  <option value="" selected="selected">- None -</option>
  <option value="foo">Foo</option>
  <option value="bar">Bar</option>
  <option value="baz">Baz</option>
</select>

Proposed resolution

I have a proposal, but I am not comfortable with it because:

  • EnumTrait is used in other propType and source plugins which may or may not be covered by this issue
  • I trigger phpunit errors with this change
diff --git a/src/EnumTrait.php b/src/EnumTrait.php
index 30b2d69c..7d05a119 100644
--- a/src/EnumTrait.php
+++ b/src/EnumTrait.php
@@ -16,13 +16,11 @@ trait EnumTrait {
    */
   protected static function getEnumOptions(array $definition): array {
     $values = array_combine($definition['enum'], $definition['enum']);
-    foreach ($values as $key => $label) {
-      if (is_string($label)) {
-        $values[$key] = ucwords($label);
-      }
+    foreach ($values as $value) {
+      $values[$value] = is_string($value) ? ucwords($value) : $value;
     }
     if (!isset($definition['meta:enum'])) {
-      return array_values($values);
+      return $values;
     }
     $meta = $definition['meta:enum'];
     // Remove meta:enum items not found in options.

API changes

Careful, we are shipping 2.0.0 next week

🐛 Bug report
Status

Active

Version

2.0

Component

Code

Created by

🇫🇷France pdureau Paris

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

Merge Requests

Comments & Activities

Production build 0.71.5 2024