我有一個嵌套的 JSON 對象,我試圖將其發送到使用 FOSRestBundle 的 Symfony API。{ "firstName": "John", "lastName": "Doe", "email": "[email protected]", "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 關注
- 142 瀏覽
添加回答
舉報
0/150
提交
取消