SDC prop could not be named variant if prop is optional

Created on 20 June 2025, 4 months ago

Problem/Motivation

Since Drupal 11.2, Drupal introduced SDC variants, all SDC having prop named variant and which are optional, will lead to an error when rendering this prop, if no value is set (NULL).
Instead of not passing this prop at all, SDC variants new capabilities will set variant to an empty string.
But SDC doesn't allow empty string, so we receive this error during the component rendering:

Twig\Error\RuntimeError occurred during rendering of component 9636f181-461a-470b-98f3-cb2efdb79401 in Page Cards (3), field components: An exception has been thrown during the rendering of a template ("[mytheme:linno-button/variant] Does not have a value in the enumeration ["outline","soft"]. The provided value is: "".")

Steps to reproduce

Install Drupal 11.2.0
Add a SDC with prop named variant

  ...
  properties:
    variant:
      type: string
      title: Button Variant
      enum:
        - "outline"
        - "soft"
   ...

Render this SDC via a controller for example

    $build = [
      '#type' => 'component',
      '#component' => 'my-theme:linno-button',
      '#props' => []
    ];

Proposed resolution

This is the code adding variant as a prop, even if no value is set.
core/lib/Drupal/Core/Render/Element/ComponentElement.php:52

 public function preRenderComponent(array $element): array {
    $props = $element['#props'];
    if (isset($element["#variant"]) && !isset($props['variant'])) {
      $props['variant'] = $element["#variant"];
    }

I suppose could be replaced by

    if (isset($element["#variant"]) && !empty($element["#variant"]) && !isset($props['variant'])) {
      $props['variant'] = $element["#variant"];
    }
🐛 Bug report
Status

Active

Version

11.2 🔥

Component

single-directory components

Created by

🇮🇱Israel heyyo Jerusalem

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