You can achieve what you want with the Groups
exclusion strategy.
For example, your Post
object might look like this:
use JMS\Serializer\Annotation as JMS; class Post { private $id; private $title; private $foos; }
Similarly, if your controller action returns a View
using serializerGroups={"all"}
, the response will contain all the fields of your entity.
If it uses serializerGroups={"withFooAssociation"}
, the response will contain foos[]
records and their affected fields.
And if it uses serializerGroups={"withoutAssociation"}
, the foos
association foos
be excluded by the serializer, and therefore it will not be displayed.
To exclude properties from the association target ( Foo
object), use the same Groups
for the properties of the target entity to get a serialization strategy.
When your serialization structure is good, you can dynamically install serializerGroups
in your controller to use different groups depending on the include
and fields
parameters (i.e. /posts?fields[]=id&fields[]=title
). Example:
// PostController::getAction use JMS\Serializer\SerializationContext; use JMS\Serializer\SerializerBuilder; $serializer = SerializerBuilder::create()->build(); $context = SerializationContext::create(); $groups = []; // Assuming $request contains the "fields" param $fields = $request->query->get('fields'); // Do this kind of check for all fields in $fields if (in_array('foos', $fields)) { $groups[] = 'withFooAssociation'; } // Tell the serializer to use the groups previously defined $context->setGroups($groups); // Serialize the data $data = $serializer->serialize($posts, 'json', $context); // Create the view $view = View::create()->setData($data); return $this->handleView($view);
I hope that I understood your question correctly and that this will be enough to help you.
source share