Closed
Description
Rendering "extra" Attributes with a PreMount
hook + OptionsResolver
will not work if followed as the doc explains it.
As from the example, if the Alert component looks like this:
#[AsTwigComponent]
final class Alert
{
public string $message;
public string $type = 'success';
#[PreMount]
public function preMount(array $data): array
{
// validate data
$resolver = new OptionsResolver();
$resolver->setDefaults(['type' => 'success']);
$resolver->setAllowedValues('type', ['success', 'danger']);
$resolver->setRequired('message');
$resolver->setAllowedTypes('message', 'string');
return $resolver->resolve($data);
}
}
Calling it like this:
<twig:Alert id="alert_id" message="My message"/>
Will throw an UndefinedOptionsException
error:
Caution
Error rendering "Alert" component: The option "id" does not exist. Defined options are: "message", "type".
We may need to resolve this incoherence by:
- Add an extra paragraph in the
PreMount
hook part, to explain how to do it with extra attributes. - Re-write the "example" preMount function doc like this:
#[PreMount]
public function preMount(array $data): array
{
// validate data
$resolver = new OptionsResolver();
+ $resolver->setIgnoreUndefined();
+
$resolver->setDefaults(['type' => 'success']);
$resolver->setAllowedValues('type', ['success', 'danger']);
$resolver->setRequired('message');
$resolver->setAllowedTypes('message', 'string');
- return $resolver->resolve($data);
+ return array_merge($data, $resolver->resolve($data));
}
I could have done a PR directly, but I want to talk about it first and discuss if it is necessary or not.
Metadata
Metadata
Assignees
Labels
No labels