Symfony 3 - How to handle JSON request with a form

11,522

Solution 1

$data = json_decode($request->getContent(), true);
$form->submit($data);

if ($form->isValid()) {
    // and so on…
}

Solution 2

I guess you can drop forms and populate->validate entities

$jsonData = $request->getContent();
$serializer->deserialize($jsonData, Entity::class, 'json', [
    'object_to_populate' => $entity,
]);
$violations = $validator->validate($entity);

if (!$violations->count()) {

    return Response('Valid entity');
}

return new Response('Invalid entity');

https://symfony.com/doc/current/components/serializer.html#deserializing-in-an-existing-object

https://symfony.com/components/Validator

Share:
11,522
Zed-K
Author by

Zed-K

Updated on June 12, 2022

Comments

  • Zed-K
    Zed-K almost 2 years

    I'm having a hard time figuring out how to handle a JSON request with Symfony forms (using v3.0.1).

    Here is my controller:

    /**
     * @Route("/tablet")
     * @Method("POST")
     */
    public function tabletAction(Request $request)
    {
        $tablet = new Tablet();
        $form = $this->createForm(ApiTabletType::class, $tablet);
        $form->handleRequest($request);
    
        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($tablet);
            $em->flush();
        }
    
        return new Response('');
    }
    

    And my form:

    class ApiTabletType extends AbstractType
    {
        public function buildForm(FormBuilderInterface $builder, array $options)
        {
            $builder
                ->add('macAddress')
            ;
        }
    
        public function configureOptions(OptionsResolver $resolver)
        {
            $resolver->setDefaults([
                'data_class' => 'AppBundle\Entity\Tablet'
            ]);
        }
    }
    

    When I send a POST request with the Content-Type header properly set to application/json, my form is invalid... all fields are null.

    Here is the exception message I get if I comment the if ($form->isValid()) line :

    An exception occurred while executing 'INSERT INTO tablet (mac_address, site_id) VALUES (?, ?)' with params [null, null]:

    I've tried sending different JSON with the same result each time:

    • {"id":"9","macAddress":"5E:FF:56:A2:AF:15"}
    • {"api_tablet":{"id":"9","macAddress":"5E:FF:56:A2:AF:15"}}

    "api_tablet" being what getBlockPrefix returns (Symfony 3 equivalent to form types getName method in Symfony 2).

    Can anyone tell me what I've been doing wrong?


    UPDATE:

    I tried overriding getBlockPrefix in my form type. The form fields have no prefix anymore, but still no luck :/

    public function getBlockPrefix()
    {
        return '';
    }