Symfony 表单:所选选项无效

Symfony form: The selected choice is invalid

提问人:mbyou 提问时间:1/7/2023 更新时间:1/8/2023 访问量:861

问:

我的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 添加选择选项,如下所示:

enter image description here

我的问题是在控制器中,表单无效。因为用户选择了一个城市,而该城市未在 LeadType ('choices' => []) 选项中提供。

这是错误:

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

如何使选择有效?

PHP 表单 symfony 验证 symfony-forms

评论

1赞 craigh 1/7/2023
使用表单事件修改表单,然后重新加载并重绘整个表单
1赞 V-Light 1/7/2023
@mbyou,由于您配置了symfony-validation,因此将除其他所有内容视为无效。因此,在您提交带有“Bar-le-Duc”的表单后,该表单不在→验证失败。'choices' => [],[][]

答:

4赞 mbyou 1/8/2023 #1

完全@craight

我在表格中添加:

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

预提交时,我更新了选项,并且只将用户选择'choices' => ['Bar-le-Duc' => 'Bar-le-Duc'],

表单在控制器中生效