我很难弄清楚如何使用Symfony表单处理
JSON请求(使用v3.0.1).
这是我的控制器:
/** * @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(''); }
我的形式:
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' ]); } }
当我发送POST请求并将Content-Type标头正确设置为application / json时,我的表单无效…所有字段都为空.
如果我评论if($form-> isValid())行,这是我得到的异常消息:
An exception occurred while executing ‘INSERT INTO tablet
(mac_address,site_id) VALUES (?,?)’ with params [null,null]:
我每次尝试发送不同的JSON,结果相同:
> {“id”:“9”,“macAddress”:“5E:FF:56:A2:AF:15”}
> {“api_tablet”:{“id”:“9”,“macAddress”:“5E:FF:56:A2:AF:15”}}
“api_tablet”是getBlockPrefix返回的内容(Symfony 3相当于Symfony 2中的表单类型getName方法).
谁能告诉我我做错了什么?
更新:
我尝试在我的表单类型中覆盖getBlockPrefix.表单字段不再有前缀,但仍然没有运气:/
public function getBlockPrefix() { return ''; }
$data = json_decode($request->getContent(),true); $form->submit($data); if ($form->isValid()) { // and so on… }