Search code examples
phpformssymfonyvalidationsymfony-forms

Symfony form: The selected choice is invalid


My symfony app have this entity:

<?php

namespace App\Entity;

class Lead
{
    private ?string $zipCode;
    private ?string $city;

    public function getZipCode(): ?string
    {
        return $this->zipCode;
    }

    public function setZipCode(string $zipCode): self
    {
        $this->zipCode = $zipCode;

        return $this;
    }

    public function getCity(): ?string
    {
        return $this->city;
    }

    public function setCity(string $city): self
    {
        $this->city = $city;

        return $this;
    }
}

And the Form LeadType is :

$builder->add('zipCode', TextType::class, [
        'attr' => [
            'placeholder' => 'Ex : 44000',
            'onchange' => 'cityChoices(this.value)',
        ]
    ])
    ->add('city', ChoiceType::class, [
        'choices' => [],
        'attr' => ['class' => 'form-control'],
        'choice_attr' => function () {return ['style' => 'color: #010101;'];},
    ]);

When the user enters a zip code, the javascript function cityChoices() add the select options using an external api like:

enter image description here

My problem is in the controller that the form is invalid. Because the user has selected a city that was not offered in the choices of LeadType ('choices' => []).

Here is the error:

0 => Symfony\Component\Form\FormError {#3703 ▼
          #messageTemplate: "The selected choice is invalid."
          #messageParameters: array:1 [▼
            "{{ value }}" => "Bar-le-Duc"
          ]

How to make the choice valid?


Solution

  • Completly @craight

    I add to the form :

    ->addEventListener(FormEvents::PRE_SUBMIT, function(FormEvent$event){
       $form = $event->getForm();
       $city = $event->getData()['city'];
       if($city){
           $form->add('city', ChoiceType::class, ['choices' => [$city => $city]]);
       }
    })
    

    When pre submit, I update choices and I put only the user select 'choices' => ['Bar-le-Duc' => 'Bar-le-Duc'],

    The form becomes valid in the controller