I'm building an API with Symfony 3 following the JSON API specification (Documentation).
When submitting new data, the request has this format :
{
"type": "entity",
"id" : null,
"attributes" : {
"name" : "Test name"
}
}
But the problem is the request does not fit the format expected by symfony's Forms because of the extra object attributes
.
So I want to be able to transform the request before the form submit in order to make the form able to populate the underlying Entity.
I have tried to register an FormEvents:PRE_SUBMIT
and do the logic in it but it seems I have no access to the Request content.
$builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) {
$data = $event->getData();
var_dump($data);
die();
});
The $event->getData()
is null
.
I have also see there is possibility to register DataTransformer
but it is registered per field, and has no access to the Request too.
I don't want to do it manually in the Controller as this will occur on all my forms (or at least the majority), so I search for a more generic way to transform the request, but at this point I can't figure out how to do this.
Thanks for help.
Your EventListener
does not have access to your Request
, nor does your Form
itself.
The best and cleanest way to do this in my opinion would be to define a custom RequestHandler
for your Forms
, extending the NativeRequestHandler
that parses your Request
by default.
Then you only need to execute $builder->setRequestHandler()
to apply this to your Forms.