Problème de validation de formulaire avec EventSubscriber

Par FACHINA, il y a 1 an


Je rencontre une erreur de validation "selected options is invalid" lors de la soumission d'un formulaire Symfony avec un champ de tags à autocomplétion.

Ma configuration :

Problème :
Malgré la bonne mise à jour des données dans le subscriber, la validation échoue.

Code :

// EventSubscriber public function onFormPreSubmit(PreSubmitEvent $event): void { if (!isset($event->getData()['tags'])) { return; } /** @var list<string> $incomingTags */ $incomingTags = $event->getData()['tags'] ?? []; /** @var Tag[] $newTags */ $newTags = []; $existingTags = $this->tagRepository->findExistingTagBySlugList($incomingTags); $existingTagsSlug = array_map(function ($v) { return $v->getSlug(); }, $existingTags); foreach ($incomingTags as $t) { if (!in_array($t, $existingTagsSlug)) { $tag = (new Tag())->setTitle($t); $this->em->persist($tag); $newTags[] = $tag; } } $this->em->flush(); // Combine existing and new tags $allTags = [...$existingTags, ...$newTags]; // Update the form data with the complete list of tags $newFormData = $event->getData(); $newFormData['tags'] = array_map(function ($tag) { return $tag->getSlug(); }, $allTags); $event->setData($newFormData); // Set the normalized data (actual Tag objects) $event->getForm()->get('tags')->setData($allTags); } //TagAutocompleteField #[AsEntityAutocompleteField] class TagAutocompleteField extends AbstractType { public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ 'class' => Tag::class, 'choice_label' => 'title', 'choice_value' => 'slug', 'attr' => [ 'data-tags' => 'true' ], 'tom_select_options' => [ 'create' => true, ], 'multiple' => true, 'required' => false, 'autocomplete' => true, 'searchable_fields' => ['title'], 'choice_lazy' => true ]); } public function getParent(): string { return BaseEntityAutocompleteType::class; } } //Form public function buildForm(FormBuilderInterface $builder, array $options): void { /** @var User $user */ $user = $this->security->getUser(); $editing = $builder->getForm()->getData()?->getId() !== null; $builder ->add('title', null, [ 'label' => 'Titre de l\'article', ]) /** ... **/ ->add('tags', TagAutocompleteField::class) ->addEventSubscriber(new TagsFieldListenerSubscriber($this->em, $this->tagRepository)) /** ... **/ ; }

Aucune réponse