Skip to content

Avoid validation errors when selecting a dependent field first, then modifying the field it relies on #35

Closed
@gremo

Description

@gremo

I've a simple form with two fields:

  • Office (headquarter)
  • User (employee) selection that depends on office selection

I want to be able to select "any user" (that doesn't belong to any office)... or select the office and see the list of users.

public function buildForm(FormBuilderInterface $builder, array $options): void
{
    $builder = new DynamicFormBuilder($builder);
    $builder
        ->add('office', ChoiceType::class, [
            'placeholder' => 'Qualsiasi sede',
            'choices' => $this->handle(new FetchCompanyOfficesMessage($options['profile'])),
            'choice_value' => fn(?CompanyOffice $c) => $c->id ?? '',
            'choice_label' => fn(?CompanyOffice $c) => $c?->name ?? '',
        ])
        ->addDependent('user', 'office', function (DependentField $field, ?CompanyOffice $office) use ($options) {
            $field->add(ChoiceType::class, [
                'choices' => $this->handle(new FetchRemoteUsersMessage($options['profile'], $office)),
                'placeholder' => 'Qualsiasi dipendente',
                'choice_value' => fn(?User $u) => $u?->id ?? '',
                'choice_label' => fn(?User $u) => $u?->fullName ?? '',
            ]);
        })
    ;
}

When you select an office, the form dynamically updates to display only the employees associated with that office. So far so good.

The issue occurs when you first select a user, then choose an office the user doesn't belong to:

liveprop

After selecting an office, the users list updates, and the previously selected user disappears (id: 35). However, the data sent to the server (as well as the live property value) still holds the old, now invalid, user. As a result, the form isn't submitted due to a validation error:

Immagine 2024-10-05 033026

Is there any option to avoid this behaviour?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions