0

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

1
  • Are you building the api? in case it it's like this then I would suggest you to do this: $context = new SerializationContext(); $context->setGroups("myGroup"); $json = $this->get("serializer")->serialize($result, 'json', $context); return new JsonResponse($json, 200, [], true); Commented Aug 8, 2017 at 9:41

1 Answer 1

1

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/"
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your answer. My controller does extend FOSRestController but I am not using jms_serializer for different reasons. Also, I'd like to stick with fosrest return syntax ( e.g : $view = $this->view($myEntity, 200)->setTemplate("default/myEntity.html.twig")->setTemplateVar('myEntity'); )
Didn't find any alternative to jms_serializer. Works well. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.