I find it difficult to determine how to handle a JSON request with Symfony forms (using v3.0.1).
Here is my controller:
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 submit a POST request with the Content-Type header set correctly in application / json, my form is invalid ... all fields are null.
Here is the error message that I get if I comment out a line if ($form->isValid()):
An exception occurred while executing INSERT INTO (mac_address, site_id) VALUES (?,?) With parameters [null, null]:
I tried sending different JSON with the same result every time:
{"id":"9","macAddress":"5E:FF:56:A2:AF:15"}{"api_tablet":{"id":"9","macAddress":"5E:FF:56:A2:AF:15"}}
"api_tablet" is what returns getBlockPrefix(Symfony 3 is equivalent to the form method getNamein Symfony 2).
Can someone tell me what I was doing wrong?
UPDATE:
getBlockPrefix . , :/
public function getBlockPrefix()
{
return '';
}