Remove form namespace in Symfony2 form (for REST A

2019-03-31 23:11发布

I'm designing REST API with Symfony2.

For POST and PUT request i'm using a 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 :

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

But I don't want this top-level namespace !

Any ideas ?

标签: php rest symfony
2条回答
一夜七次
2楼-- · 2019-04-01 00:04

I've used Symfony forms for JSON based APIs. You just need to change your getName() method to return '':

public function getName()
{
    return '';
}

This, cobined with the FOSRestBundle, made working with POSTed data very easy.

查看更多
祖国的老花朵
3楼-- · 2019-04-01 00:10

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:

$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.

查看更多
登录 后发表回答