Search code examples
phpsymfonysymfony-forms

Symfony UX LiveCollectionType no errors shown when submitting empty form


I have a quick question regarding a UX LiveCollectionType: https://symfony.com/bundles/ux-live-component/current/index.html#using-livecollectiontype

Let's say I have a very basic UX Live Component, that only renders the form and processes the submission.

I add the LiveCollectionTrait and initialize the form, and create a function for submitting the form:

//rest of the code

use ComponentWithFormTrait;
use LiveCollectionTrait;

protected function instantiateForm(): FormInterface
{
    return $this->createForm(ParentFormType::class);
}

#[LiveAction]
public function saveIt(): \Symfony\Component\HttpFoundation\RedirectResponse
{
    $this->submitForm();
    $form = $this->getForm();

    /**  FormDataEntity $formEntity */
    $formEntity = $form->getData();
    $this->entityManager->persist($formEntity);
    $this->entityManager->flush();

    return $this->redirectToRoute('home');
}

This ParentFormType form contains just one field:

//rest of the code of ParentFormType

$builder
    ->add('child', LiveCollectionType::class, [
        'entry_type' => ChildEmbeddedType::class,
        'error_bubbling' => false,
        'constraints' => [
            new Valid(),
        ],
    ])
;

//rest of the code

Let's say, for simplicity sake, ChildEmbeddedType contains just one field:

//rest of the code of ChildEmbeddedType

->add('name', TextType::class, [
    'label' => 'name',
    'required' => true,
    'constraints' => new Length(
        min: 2,
    ),
]);

//rest of the code of ChildEmbeddedType

I render the form inside the component's Twig template as I should:

<div{{ attributes }}>
    {{form_start(form) }}
    {{form_end(form) }}
    <button type="button" data-action="live#action" data-live-action-param="saveIt" formnovalidate>submit</button>
</div>

Alternatively, if I define the form field, explicitly with an error var, the same behavior is observed:

    <div{{ attributes }}>
        {{ form_start(form) }}
           {{ form_row(form.name) }}
           {{ form_errors(form.name) }}
        {{ form_end(form) }}
        <button type="button" data-action="live#action" data-live-action-param="saveIt" formnovalidate>submit</button>
    </div>

On my home.html.twig I include this component:

<twig:FormComponent />

I load the page, add a new collection type, enter 1 character into my "name" field, the component automatically re-renders, and I get a neat validation message right below the form field: "The value is too short, it should have" etc. etc.

So validation works.

I reload, the page, add a new collection type, but this time I leave the form field empty.

I click "submit". The component re-renders, and the Profiler shows me the Validation errors. The form field, however, does not reflect this. It simply renders a form field without errors (or any indication thereof).

When I loop over the errors in Twig:

{% set formErrors = form.vars.errors.form.getErrors(true) %}

{% if formErrors|length %}
  {% for error in formErrors %}
    {{ error["message"] }}
  {% endfor %}
{% endif %}

I see the messages, e.g.:

This value should not be blank.

For each of the fields that should have a value but don't actually show it.

In this example, with one field, I can show a generic error message saying; check the field because it's empty.

But as the embedded form is more complex, with multiple entries, it may get more difficult for the user to spot the field they forgot.

Do any of you have an idea how to get the individual fields to show the error on submitting an empty LiveCollectionType? :)

  • I tried to manually validate the form in the Live Component, which returned the same result,
  • I tried to add a live#action|prevent instead of live#action, with the same result.
  • I moved the submit between the form tags, unfortunately with the same result.
  • I removed all form field formatting and reverted to the default bootstrap form theme to see if my custom template was causing this, unfortunately with the same result.
  • I tried to extract the error message from form.vars.errors.form.getErrors(true) and display it below the field, but this simply duplicated the error message on wrong value entry but did nothing on submitting an empty form.

Solution

  • Although it is not explicitly mentioned, adding 'empty_data' => '' to each of the required fields in the embedded form triggers the validation properly.

    As an example:

            ->add('fullName', TextType::class, [
                'label' => $this->translator->trans('Full name'),
                'required' => true,
                'constraints' => new Length(
                    min: 2,
                ),
                'empty_data' => '',
            ])
    

    Even though you may have validation constraints on the parent form, an entity, the form field itself, etc. etc. Adding the empty_data seems to be the only option that works.