k0pernikus
k0pernikus

Reputation: 66500

How to get groups working for JMSSerializerBundle and FOSRestBundle?

I am trying to set up different groups to achieve different types of serialization of my entities depending on the context.

My config looks like this:

My\FooBundle\Entity\Asset:
    exclusion_policy: ALL
    access_type: public_method
    properties:
        id:
            access_type: property
            expose: true
            groups: [fnord]
        name:
            expose: true
        path:
            expose: true
        isInQuarantine:
            expose: true
            groups: [baz]

I expect that the group having properties should not be exposed unless the group is set.

I am trying to set the group in my controller via:

    $view->setSerializationContext(SerializationContext::create()->setGroups(array('fnord')));

Yet there is no effect on what is exposed and what isn't. Even if I do not try to change the SerializationContext, the groups options seems to be always ignored.

I know that my config is working because I can toggle the properties via the expose flag.

Yet what am I doing wrong here?

Upvotes: 4

Views: 4607

Answers (1)

Guiguiboy
Guiguiboy

Reputation: 41

I know this question is a bit old, but it may help others. I encountered a similar issue. This was because I had in my controler (that extends FOSRestControler) a method with multiple calls to

$this->getView()

You have to notice that this method creates a new View object.

That means, if you call multiple getView methods, the context get reset.

Have a look at the following code that worked for my app :

use FOS\RestBundle\Controller\FOSRestController as Controller;    
class RestController extends Controller
{
   public function getUserAction($username)
    {
        $view = $this->view();
        $view->setSerializationContext(SerializationContext::create()->setGroups(array('Product')));

        $user = $this->getDoctrine()->getManager()->getRepository('VendorUserBundle:User')->findOneByUsername($username);
        if(!is_object($user))
        {
            throw $this->createNotFoundException();
        }
        $view->setData($user);
        return $view;
    }
}

In Model.User.yml file :

FOS\UserBundle\Model\User:
    exclusion_policy: ALL
    properties:
        username:
            expose: true
            groups: [fnord]
        email:
            expose: true
            groups: [Product]
        enabled:
            expose: true
            groups: [Product]
        roles:
          expose: true
          groups: [Product]

Gives the following output :

{"email":"[email protected]","enabled":true,"roles":["ROLE_XXX"]}

I didn't have any cache related problems (dev env used).

Upvotes: 2

Related Questions