使用Sf表单,但无法通过ChoiceType验证值
表格:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$countryChoiceArr = [];
foreach ($options['countries'] as $country) {
if (array_key_exists('fullName', $country) && array_key_exists('countryCode', $country)) {
$countryChoiceArr[$country['fullName']] = $country['countryCode'];
}
}
$builder
->add('choice', ChoiceType::class, [
'choices' => $countryChoiceArr,
])
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'countries' => [],
]);
$resolver->setAllowedTypes('countries', 'array');
}
数组是$ countryChoiceArr = ['一个'=>'一个','两个'=>'两个'] 我发现问题是当我在变量中传递$ countryChoiceArr时,如果在括号中传递相同的值,则表单会出错,例如
'choices' => ['one' => 'one', 'two' => 'two']
没有错误。
表单错误本身:
#message: "Unable to reverse value for property path "[country]": The choice "ago" does not exist or is not unique."
#code: 0
#file: "\vendor\symfony\form\Form.php"
#line: 1141
-previous: Symfony\Component\Form\Exception\TransformationFailedException {#558 ▼
-invalidMessage: null
-invalidMessageParameters: []
#message: "The choice "ago" does not exist or is not unique."
#code: 0
#file: "ChoiceToValueTransformer.php"
我已经看到一些涉及EventListener和DataType更改的解决方案,但是,这应该更简单,因为我传递的是同时具有键和值的两个字符串数组,只需要从下拉列表中进行选择并以字符串形式获取值即可。
将感谢您的建议。