提问人:mbyou 提问时间:1/7/2023 更新时间:1/8/2023 访问量:861
Symfony 表单:所选选项无效
Symfony form: The selected choice is invalid
问:
我的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"
]
如何使选择有效?
答:
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'],
表单在控制器中生效
评论
'choices' => [],
[]
[]