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 ?
I've used Symfony forms for JSON based APIs. You just need to change your
getName()
method to return''
:This, cobined with the FOSRestBundle, made working with POSTed data very easy.
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:That's why you have to return a name in the form type class:
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:
An empty string —
''
— instead ofnull
works as well.