Symfony 3-如何使用表单处理JSON请求 [英] Symfony 3 - How to handle JSON request with a form

查看:107
本文介绍了Symfony 3-如何使用表单处理JSON请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难弄清楚如何使用Symfony表单(使用v3.0.1)处理JSON请求.

I'm having a hard time figuring out how to handle a JSON request with Symfony forms (using 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'
        ]);
    }
}

当我发送Content-Type标头正确设置为application/json的POST请求时,我的表单无效...所有字段均为空.

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

这是我在注释if ($form->isValid())行时得到的异常消息:

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

执行'INSERT INTO tablet'时发生异常 (mac_address,site_id)VALUES(?,?)',带有参数[null,null]:

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

我尝试每次发送具有相同结果的不同JSON:

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"}}
  • {"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方法).

"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?

更新:

我尝试覆盖表单类型中的getBlockPrefix.表单字段不再有前缀,但仍然没有运气:/

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…
}

这篇关于Symfony 3-如何使用表单处理JSON请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆