Description
Let me preface by saying "yea I know this aint probably the right place to ask", but I am fairly certain this problem is unwanted behaviour...but I'd be glad to be proven wrong.
The LiveComponent would be pretty simple:
#[AsLiveComponent(template: 'some_template.html.twig')]
class SomeLiveComponent extends AbstractController
{
use DefaultActionTrait, ComponentWithFormTrait;
protected function instantiateForm(): FormInterface
{
return $this-createForm(SomeFormType::class);
}
#[LiveAction]
public function save(): ?Response
{
try {
/// ... do some persistence
} catch (\Throwable $e) {
$error = new FormError('An error occurred');
$this->form->addError($error); // <--- How would I display this error in my template?
}
}
The template, as simple as can be:
{# some_template.html.twig #}
{{ form_start(form,
{
'attr': {
'data-action': 'live#action:prevent',
'data-live-action-param': 'save'
}
})
}}
{{ form_errors(form) }} <!-- The Error should be displayed here -->
{{ form_row(form.someField) }}
<button type="submit" data-loading="action(save)|addAttribute(disabled)">Submit</button>
{{ form_end(form) }}
A somewhat ugly workaround would be adding a $formErrors array property to the component and populating it with whatever error-messages occur. You could then simply display all those messages in the template, though due to how detached that is from the normal symfony form workflow I would rather avoid this.
I understand that throwing a UnprocessableEntityHttpException() makes turbo re-render the HTML it receives in the response, so the "save()" function should throw that whenever it fails. But the errors are not added to the response HTML anyway - either because the HTML has already been rendered or the FormErrors are removed manually...though I have no idea
I tried adding a writable LiveProp array property to my component which would be populated with FormErrors throughout the submit process - similar to the hacky $formErrors array property mentioned above. But the "instantiateForm()" function would add these errors manually to the form - but that does not work either.
Any pointers would be helpful.