phpjsonsymfonyfosrestbundle

Send Nested Json to a Symfony Form


I have a nested JSON object that I am trying to send to a Symfony API which is using FOSRestBundle.

{
    "firstName": "John",
    "lastName": "Doe",
    "email": "john.doe@gmail.com",
    "responses": [
        {"1": "D"},
        {"2": "B"},
        {"3": "C"},
        {"4": "F"}
    ]
}

But I get the following error:

{
"code": 400,
"message": "Validation Failed",
"errors": {
    "children": {
        "firstName": [],
        "lastName": [],
        "email": [],
        "responses": {
            "errors": [
                "This value is not valid."
            ]
        }
    }
}

}

This is my 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',  TextType::class, [
            'constraints' => [
                new NotBlank(),
                new Length(['min' => 3]),
            ]
        ])
        ->add('email',  TextType::class, [
            'constraints' => [
                new NotBlank(),
                new Length(['min' => 3]),
            ]
        ])
        ->add('responses');
    ;
}

And this is my controller method:

/**
 * @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
        )
    );
}

I am confused as there is no form validation $responses.

I have tried to implement the solution offered on this link: How to process nested json with FOSRestBundle and symfony forms

But I get the error 'You cannot add children to a simple form. Maybe you should set the option "compound" to true?

Can anyone offer advice on how to resolve this?


Solution

  • hello i think the issue is on responses. try using CollectionType. In this exemple using ChoiceType for each object in your collection. See here: 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',
         ],
     ],
    ]);