Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
gremo opened this issue Oct 5, 2024 · 1 comment

Comments

@gremo
Copy link

gremo commented Oct 5, 2024

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?

@gremo
Copy link
Author

gremo commented Oct 5, 2024

Closing if favour of symfony/ux#2240

@gremo gremo closed this as completed Oct 5, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant