简体   繁体   中英

Remove form namespace in Symfony2 form (for REST API)

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 ?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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