Symfony ChoiceType 动态填充选项并初始化空选项数组

Jos*_*e M 2 php symfony

我试图在 Symfony 3.0.9 中定义一些 ChoiceType,其中根据动态创建的选项数量填充了 ajax,但随后验证表单显示所选选项无效。

我这样定义 ChoiceType:

->add('position', ChoiceType::class, [
    'placeholder' => 'Select position',
    'choices'  => [],
    'attr' => [
       'class' => 'form-control choice-position'
    ],
 ])
Run Code Online (Sandbox Code Playgroud)

我得到的错误是:

Symfony\Component\Validator\ConstraintViolation
Object(Symfony\Component\Form\Form).children[lessonGroups].children[0].children[position] = 1

Caused by:
Symfony\Component\Form\Exception\TransformationFailedException
Unable to reverse value for property path "position": The choice "1" does not exist or is not unique

Caused by:
Symfony\Component\Form\Exception\TransformationFailedException
The choice "1" does not exist or is not unique
Run Code Online (Sandbox Code Playgroud)

我不知道是否需要任何进一步的信息。

谢谢!

got*_*oto 6

因为你的定义不包括任何选择 ( 'choices' => [],) Symfony 检测到比用户尝试提交的结果不在最初的授权结果中。

您可以设置包含所有可用值的初始选项数组,或者您可以使用以下方法禁用该验证:

$builder->get('yourField')->resetViewTransformers();
Run Code Online (Sandbox Code Playgroud)