亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

將嵌套 Json 發送到 Symfony 表單

將嵌套 Json 發送到 Symfony 表單

PHP
紅糖糍粑 2023-10-22 21:34:05
我有一個嵌套的 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',

     ],

 ],

]);


查看完整回答
反對 回復 2023-10-22
?
慕桂英546537

TA貢獻1848條經驗 獲得超10個贊

我知道這不是真正的問題,但萬一其他人像我一樣在搜索如何將嵌套對象放入 FOSRestBundle 注釋后來到這里:我查看了我的代碼庫并找到了 和 約束,我認為它們將Symfony\Component\Validator\Constraints\Collection提供Symfony\Component\Validator\Constraints\Composite服務我很好。



查看完整回答
反對 回復 2023-10-22
  • 2 回答
  • 0 關注
  • 142 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號