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"];
}