3

I'm trying to convert an entity to a associative array.
It seems that the method toArray() is not available for entity objects.

Reading Symfony doc, it seems I should use the SerializerInterface.
After enabling it, I can't seems to find the right syntax to convert my entity into an associative array.

Can someone correct my code please?

use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\SerializerInterface;

// -----------------------

public function salleAction(Request $request, Projet $projet, SerializerInterface $serializer) {
    return this->json(array(
        'projet'=>$serializer->serialize($projet, new ObjectNormalizer())
    ));
}

With the code above, I'm getting this error message

Warning: Illegal offset type in isset or empty

If I replace new ObjectNormalizer() by 'jsons', I'm getting the next error message:

A circular reference has been detected when serializing the object of class "AppBundle\Entity\Projet" (configured limit: 1)

1 Answer 1

7

I suggest you to add the following method to an object, that needs to be converted

public function toArray()
{
    return get_object_vars($this);
}

and use it everywhere $array = $projet->toArray();

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

2 Comments

It's working, but some things aren't "right". First, Datetime and properties on the owning side (entity relations) are objects instead of simple value. Second, properties on the inverse side are included as emtpy object, I would like to exclude them. Is it possible to fix this?
this is just a basic example, you are able to customize this method for your specific need, that's why I suggested to attach the method to a an entity, because the method is specific for each particular case.

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.