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": "[email protected]",
    "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:

/**
 * @RestPost(
 *     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?

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *