ux
ux copied to clipboard
[UX] Live component - form select required not initialized
Symfony version(s) affected
6.3.10
Description
Class: Symfony\UX\LiveComponent\ComponentWithFormTrait::extractFormValues
Doesn't extract required values for select / entity type field:
The default value should be '1'.
This is the FormType:
->add('project', EntityType::class, [
'class' => Project::class,
'label' => 'label.project',
'required' => true,
'multiple' => false,
'choice_label' => fn ($project) => $project->getName(),
])
How to reproduce
Create a form type with ux live component and required entity type field. https://symfony.com/bundles/ux-live-component/current/index.html#forms
Possible Solution
If select / entity type and required, extract the default value
Additional Context
No response
Hey, thanks for your report! There has not been a lot of activity here for a while. Is this bug still relevant? Have you managed to find a workaround?
Hello? This issue is about to be closed if nobody replies.
Hey,
I didn't hear anything so I'm going to close it. Feel free to comment if this is still relevant, I can always reopen!
Hello, I have exactly the same problem !
Same problem, cannot submit live form with default values for select and entity types
How would you handle this ?
@smnandre the solution proposed by @BriceFab seems to be a goode idea, The values should be extracted and defined in ComponentWithFormTrait::extractFormValues.
Actually to make my form works, I had to do a dirty workaround in the form:
public function finishView(FormView $view, FormInterface $form, array $options): void
{
$this->initChoiceValue($view, 'notation');
}
private function initChoiceValue(FormView $view, string $key): void
{
if ($view[$key]->vars['value'] === "" && array_key_exists('choices', $view[$key]->vars) && count($view[$key]->vars['choices']) > 0) {
$view[$key]->vars['value'] = key($view[$key]->vars['choices']);
}
}
Would one of you people be ready to open a PR ?
(We can iterate on "details" things, but this could be a good base :))
I can do it but not right away, I'm overwhelmed in the short term and I already have another PR to create and submit to you following another bug found. If someone else can do it that's great, otherwise I'll take care of it as soon as possible
Something like this ?
// ...
if ($child->vars['required'] && $values[$name] === null) {
// Select the first element if available (can be an empty placeholder)
if (0 < count($choices = $child->vars['choices'] ?? [])) {
$values[$name] = reset($choices);
continue;
}
throw new UnprocessableEntityHttpException(sprintf('The required field "%s" is missing and has no default value.', $name));
}