将嵌套 Json 发送到 Symfony 表单

Send Nested Json to a Symfony Form

我有一个嵌套的 JSON 对象,我正试图将其发送到使用 FOSRestBundle 的 Symfony API。

{
    "firstName": "John",
    "lastName": "Doe",
    "email": "john.doe@gmail.com",
    "responses": [
        {"1": "D"},
        {"2": "B"},
        {"3": "C"},
        {"4": "F"}
    ]
}

但我收到以下错误:

{
"code": 400,
"message": "Validation Failed",
"errors": {
    "children": {
        "firstName": [],
        "lastName": [],
        "email": [],
        "responses": {
            "errors": [
                "This value is not valid."
            ]
        }
    }
}

}

这是我的表单类型:

/**
 * @param FormBuilderInterface $builder
 * @param array $options
 */
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('firstName',  TextType::class, [
            'constraints' => [
                new NotBlank(),
                new Length(['min' => 3]),
            ]
        ])
        ->add('lastName',  TextType::class, [
            'constraints' => [
                new NotBlank(),
                new Length(['min' => 3]),
            ]
        ])
        ->add('email',  TextType::class, [
            'constraints' => [
                new NotBlank(),
                new Length(['min' => 3]),
            ]
        ])
        ->add('responses');
    ;
}

这是我的控制器方法:

/**
 * @Rest\Post(
 *     path="/api/report"
 * )
 * @param Request $request
 * @return Response
 */
public function post(Request $request)
{
    $form = $this->createForm(ReportType::class);
    $form->submit($request->request->all());

    if (false === $form->isValid()) {
        return $this->handleView(
            $this->view($form)
        );
    }

    return $this->handleView(
        $this->view(
            [
                'status' => 'ok',
            ],
            Response::HTTP_CREATED
        )
    );
}

我很困惑,因为没有表单验证 $responses。

我已尝试实施针对此 link 提供的解决方案:

但我收到错误消息“您不能将子项添加到简单表单。也许您应该将选项“复合”设置为 true?

任何人都可以提供有关如何解决此问题的建议吗?

您好,我认为问题出在回复上。尝试使用 CollectionType。在此示例中,为集合中的每个对象使用 ChoiceType。看这里:https://symfony.com/doc/current/reference/forms/types/collection.html#entry-options

->add('responses', CollectionType::class, [
 'entry_type'   => ChoiceType::class,
 'entry_options'  => [
     'choices'  => [
         '1' => 'D',
         '2' => 'A',
     ],
 ],
]);