Symfony2 FOSRestBundle return entity fields contained in form

458 views Asked by At

I'm using FOSRestBundle in Symfony2 to provide a REST-service.

Currently my controller returns an entity when a resource is requested (e.g. /users/40). The frontend contains a form which allows to manipulate this resource and sends it back using PUT. The controller uses a form to process the data.

My problem is, that the form has less fields than the whole entity (id and password_hash are good examples). I came to the conclusion that sending the whole entity to the client is a bad idea. Instead, I want FOSRestBundle to send only the entity fields which are avaiable in the form.

So I just tried:

return $this->createForm(UserType::class, $entity);

The JSON structure returned from the server by FOSRestBundle looks very good. But unfortunately it doesn't contain values.

Of course, it doesn't - the form is not bound. And at this point it doesn't make sense to bind data. Hence I need to find another solution.

This use case will be very common in my applications. So I wonder if there was no easy / standard way to achieve this.

(P.S. I use Angular JS in the frontend. I simply attach the entity resource JSON to the scope and use symfony form templates to generate form fields which automatically are bound to the correct object of the scope)

1

There are 1 answers

0
mickadoo On BEST ANSWER

The standard way to define what should be returned from FOS is to use serializer groups and either the Symfony serializer component or the JMS serializer.

In both cases you define groups on your entity properties:

// in the entity
use Symfony\Component\Serializer\Annotation\Groups;

class Story
{
    /**
     * @Groups({"story"})
     *
     * @var int
     */
    private $id;

And then:

 // in the controller
 * @Rest\View(serializerGroups={"story"})
 * @Rest\Route("stories")
 *
 * @return Story[]
 */
public function getStoriesAction()

Which will return you an object or objects with the properties matching the controller serializer groups exposed.