Skip to content
Snippets Groups Projects

Resolve #3455942 "Api render component with default props values from config"

All threads resolved!
@@ -12,6 +12,7 @@ use Drupal\experience_builder\Plugin\DataType\ComponentTreeHydrated;
use Drupal\experience_builder\Plugin\DataType\ComponentTreeStructure;
use Drupal\experience_builder\Plugin\Field\FieldType\ComponentTreeItem;
use Drupal\node\Entity\Node;
use Drupal\user\Entity\User;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
@@ -103,9 +104,17 @@ final class SdcController extends ControllerBase {
assert(!empty($component_info));
$component = array_values($component_info)[0];
$metadata = $component->metadata;
$properties = $metadata->schema['properties'] ?? [];
foreach ($properties as $prop_name => $prop_info) {
self::populatePropValues($build, [], $prop_name, $prop_info);
$component_config = Component::loadByComponentMachineName($component_id);
assert($component_config instanceof Component);
foreach (array_keys($metadata->schema['properties'] ?? []) as $prop_name) {
$default_static_prop_source = $component_config->getDefaultStaticPropSource($prop_name);
if ($default_static_prop_source) {
$build['#props'][$prop_name] = $default_static_prop_source->evaluate(
// @todo Either remove the need for passing in a host entity (it's not necessary for static prop sources!), or … actually provide that context here. The latter seems preferable, to allow for context-aware components in the future. As long as we only support StaticPropSources here, this will suffice.
User::create([])
);
}
}
$rendered_component = $this->renderer->render($build);
@@ -215,43 +224,4 @@ HTML;
]);
}
/**
* Assign values to props in the SDC render array.
*
* @param array<string, mixed> $build
* The render array.
* @param array<string, mixed> $values
* Already defined prop values.
* @param string $prop_name
* The prop being checked.
* @param array<string, mixed> $prop_info
* The prop's metadata.
*/
private function populatePropValues(array &$build, array $values, string $prop_name, array $prop_info):void {
$value = '';
if (isset($prop_info['examples'])) {
if ($values) {
$value = $prop_info['examples'][$values[$prop_name]] ?? $prop_info['examples'][0];
}
else {
$value = $prop_info['examples'][0];
}
}
elseif (isset($prop_info['enum'])) {
$value = $prop_info['enum'][0];
}
elseif (isset($prop_info['type'][1]) && $prop_info['type'][1] === 'object') {
if (isset($prop_info['format']) && $prop_info['format'] === 'uri') {
$value = 'https://drupal.org';
}
elseif ($prop_info['type'][0] !== 'string') {
$value = new $prop_info['type'][0]();
}
}
elseif ($prop_info['type'][0] === 'object') {
$value = [];
}
$build['#props'][$prop_name] = $value;
}
}
Loading