1

Hi !

i'd like to transform data before sending it to the view. The view is json response using FOSRestBundle.

For example, I have a Product entity with field Category, that is a reference to a Category Entity. On the output, i'd like to not to display json with the whole category, but rather only its ID field.

Of course, you can further process the entity in the Controller to return only specific field from the category, but..

I wanted to ask, if there's any "standard" solution how to do that, maybe using annotation?

Thank you

1 Answer 1

2

I reckon the best practice or standard way to achieve what you want (filtering/processing entity data before return as JSON to view), is to make use of serializer. You can consider using the Symfony Serializer Bundle: http://symfony.com/doc/current/components/serializer.html or the JMS Serializer: http://jmsyst.com/libs/serializer.

I myself recommend the JMS one, it has really good documentation, the definition is completely controlled through annotation, and a well-thought events system and a few feature I can list as follows:

-- Expose / Exclude specific entity attributes.

-- Create Virtual Property (attributes) for the entity once it converted to JSON. (So for example if you have Entity Product with attribute Price and you want to have a calculated field in the JSON object call taxPrice you can achieve it).

-- Access Control who can access which attributes/entities by categorising attributes to different groups.

-- Pre Serialization and Post Serialization events so you can tweak the data even further.

I can say the Serializer works so well with the Forest Bundle that once you get used to it, you can hardly write your project the different way :D.

Sign up to request clarification or add additional context in comments.

Comments

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.