简体   繁体   English

以Symfony2格式删除表单命名空间(对于REST API)

[英]Remove form namespace in Symfony2 form (for REST API)

I'm designing REST API with Symfony2. 我正在使用Symfony2设计REST API。

For POST and PUT request i'm using a FormType. 对于POST和PUT请求,我使用的是FormType。 Something like : 就像是 :

class EmailType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('subject', 'textarea')
        [...]
        ;
    }

    public function getName()
    {
        return 'email';
    }
}

But when I POST, i'm must pass fields with a namespace like : 但是当我发布POST时,我必须传递具有名称空间的字段:

{
    "email": {
        "subject": "subject"
    }
}

But I don't want this top-level namespace ! 但我不想要这个顶级命名空间!

Any ideas ? 有任何想法吗 ?

A form type has to have a name because if you register it as a service tagged as a form type, you need to somehow reference it. 表单类型必须具有名称,因为如果将其注册为标记为表单类型的服务,则需要以某种方式引用它。 In the following code snippet, email is the name of the form type: 在以下代码段中, email是表单类型的名称:

$form = $this->formFactory->create('email', $email);

That's why you have to return a name in the form type class: 这就是为什么你必须在表单类型类中返回一个名称:

public function getName()
{
    return 'email';
}

So, instead of creating a form type without a name, just create a form — a particular instance of that form type — with an empty name: 因此,不是创建没有名称的表单类型 ,而是创建一个表单 - 该表单类型的特定实例 - 使用空名称:

$form = $this->formFactory->createNamed(null, 'email', $email);

An empty string — '' — instead of null works as well. 空字符串 - '' - 而不是null也可以。

I've used Symfony forms for JSON based APIs. 我已经为基于JSON的API使用了Symfony表单。 You just need to change your getName() method to return '' : 您只需要将getName()方法更改为''

public function getName()
{
    return '';
}

This, cobined with the FOSRestBundle , made working with POSTed data very easy. 这与FOSRestBundle相结合 ,使得处理POSTed数据非常容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM