我有一个嵌套的 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?任何人都可以提供有关如何解决此问题的建议吗?
2 回答
江户川乱折腾
TA贡献1851条经验 获得超5个赞
你好,我认为问题出在回应上。尝试使用 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',
],
],
]);
慕桂英546537
TA贡献1848条经验 获得超10个赞
我知道这不是真正的问题,但万一其他人像我一样在搜索如何将嵌套对象放入 FOSRestBundle 注释后来到这里:我查看了我的代码库并找到了 和 约束,我认为它们将Symfony\Component\Validator\Constraints\Collection
提供Symfony\Component\Validator\Constraints\Composite
服务我很好。
- 2 回答
- 0 关注
- 101 浏览
添加回答
举报
0/150
提交
取消