I am using FOSrestBundle in my Symfony2 project. I have a view created like this:
$view = $this
->view(array(
'form' => $this->formHandler->getForm()->createView(),
'translation' => $translation,
), Response::HTTP_OK)
->setTemplate('MyBundle:Translation.html.twig');
Where $translation
is an object of my own bundle. The thing is when I call the $this->handleView($view)
, FosRestBundle use JMS serializer to serialize the data of my view (the form and the translation object) but my translation object have a lot of attributes useless in my case and the response is far too big for what I am trying to do.
I decide to use the group annotation to only retrieve useful attributes.
Here is the context with the view
group:
$context = SerializationContext::create()->setGroups(array('view'));
$view->setSerializationContext($context);
And in my Translation model I can set the ExclusionPolicy to all
and add usefull attributes to the view
group. It is working but with this configuration (the group view
in the serialization context) my form object (which is a Symfony\Component\Form\FormView
) is serialized to {}
How can I use a group for my Translation model but still serialize my FormView object ?
If you're using annotations the JMS serializer has exclusion policies for each class, which you can see here.
I would suggest instead to default to exclude all and add the serializer groups annotation on only properties you want to expose. You can add multiple groups, so in this case your serializer context could have the groups "form" and "translationBasic", then add the "form" group to all properties on formView and "translationBasic" to just those you want on the Translation class.