php Symfony形式:所选选项无效

ql3eal8s  于 2023-01-08  发布在  PHP
关注(0)|答案(1)|浏览(130)

我的symfony应用程序有此实体

<?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;
    }
}

表格LeadType为:

$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;'];},
    ]);

当用户输入邮政编码时,javascript函数 * cityChoices()* 使用外部API添加选择选项,如:

我的问题是控制器中的表单是无效的。因为用户选择了一个城市,而这个城市在LeadType的选项中没有提供('choices'=〉[])。
下面是错误:

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

如何使选择有效?

moiiocjp

moiiocjp1#

完全正确
我在表格中添加:

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

在预提交时,我更新了选项,并仅将用户选择'choices' => ['Bar-le-Duc' => 'Bar-le-Duc'],
表单在控制器中生效

相关问题