将嵌套的Json发送到Symfony表单

问题描述

我有一个嵌套的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."
            ]
        }
    }
}

}

这是我的FormType:

/**
 * @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',]
        ])
        ->add('email',]
        ])
        ->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
        )
    );
}

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

我尝试实现此链接上提供的解决方案: How to process nested json with FOSRestBundle and symfony forms

但是我收到错误消息“您无法将孩子添加到简单表单中。也许您应该将“ compound”选项设置为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',],]);

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...