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 '';
}
$data = json_decode($request->getContent(), true);
$form->submit($data);
if ($form->isValid()) {
// and so on…
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With