Search code examples
symfonyfosrestbundlesymfony-2.8serialization

Symfony2, FOSRestBundle : Serialization groups return empty


I am using FOSRest Bundle to build a small API in which I'd like to return a resource but only exposing some properties. I am using Symfony's default Serializer.

Here is my entity :

class myEntity
{
     private foo;

     * @Groups({"myGroup"})
     private bar;

     getFoo(){...}
     getBar{...}
}

And my controller :

* @ParamConverter("myEntity ")
public function getAction(myEntity $myEntity)
{    
    $context = new Context();
    $context->addGroups('myGroup');

    $view = $this->view($myEntity, 200)->setTemplate("default/myEntity.html.twig")->setTemplateVar('myEntity');
    $view->setContext($context);

    return $this->handleView($view);
}

When I try to execute my controller, I get an empty object as a response : {} If I remove the setContext() part, I get my whole entity including properties I don't want.

What am I doing wrong ? Thanks


Solution

  • First of all your controller should extend the FOSRestController As a response you are can return JsonResponse, like this:

    $context = new SerializationContext();
    $context->setGroups("myGroup");
    $json = $this->get("serializer")->serialize($result, 'json', $context);
    return new JsonResponse($json, 200, [], true);
    

    I also recommend you to move your serializer configuration to the YAML file, as described here

    Use exclusion_policy to exclude all of properties by default and add then for certain groups.

    AppBundle\Entity\EntityClass:
      exclusion_policy: ALL
    

    In the JMS serializer configuration in your config.yml file you have to specify the directory where you put all off serialize configurations, like this:

    jms_serializer:
        metadata:
            directories:
                APP:
                    namespace_prefix: "AppBundle"
                    path: "@AppBundle/Resources/config/serializer/"