【问题标题】:Send Nested Json to a Symfony Form将嵌套的 Json 发送到 Symfony 表单
【发布时间】:2023-03-19 03:55:02
【问题描述】:

我有一个嵌套的 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。

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

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

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

【问题讨论】:

  • 自动“表单验证”来自表单类型,这取决于表单的定义方式。报告实体的响应属性(getter/setter)可能会对此有所了解。如果不设置表单类型,则会猜测表单类型。 $request->request->all 可能会反序列化整个对象,因此您有一个用于响应字段的数组数组,这可能不适用于自动猜测的表单类型...

标签: php json symfony fosrestbundle


【解决方案1】:

您好,我认为问题在于响应。尝试使用 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',
     ],
 ],
]);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-16
    • 1970-01-01
    • 2017-03-01
    相关资源
    最近更新 更多