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 ''
:
public function getName()
{
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:
$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.