Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony 3 - How to handle JSON request with a form

Tags:

json

php

symfony

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 '';
}
like image 566
Zed-K Avatar asked Jan 05 '16 18:01

Zed-K


1 Answers

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

if ($form->isValid()) {
    // and so on…
}
like image 168
Anton Avatar answered Sep 20 '22 14:09

Anton