8

I run into problem tied to circular reference in Symfony, that I suspect to be caused by the serializer but I haven't found any answers yet. Here are the entities that I've created, the route and the controller. Any suggestions in this regard will be much appreciated.

User.php

class User
{
    /**
      * @var int
      *
      * @ORM\Column(name="id", type="integer")
      * @ORM\Id
      * @ORM\GeneratedValue(strategy="AUTO")
    */
    private $id;

    /**
      * @ORM\OneToMany(targetEntity="Dieta", mappedBy="user")
    */
    private $dietas;
    public function __construct()
    {
       $this->dietas = new ArrayCollection();
    }
   //...
   //...
}

Dieta.php

    class Dieta
        {
            /**
             * @var int
             *
             * @ORM\Column(name="id", type="integer")
             * @ORM\Id
             * @ORM\GeneratedValue(strategy="AUTO")
             */
            private $id;

            /**
             * @ORM\ManyToOne(targetEntity="User", inversedBy="dietas")
             * @ORM\JoinColumn(name="users_id", referencedColumnName="id")
             */
            private $user;
            public function __construct()
            {
                $this->user = new ArrayCollection();
            }

            //...
            //... 
        }

Route

/**
 * @Route("dietas/list/user/{id}", name="userDietas")
 */

Method of DietaController.php

public function userListAction($id)
    {
        $encoders = array(new XmlEncoder(), new JsonEncoder());
        $normalizers = array(new ObjectNormalizer());
        $serializer = new Serializer($normalizers, $encoders);

        $user = $this->getDoctrine()
            ->getRepository('AppBundle:User')->find($id);

        $dietaDatas = $user->getDietas();


        if(!$dietaDatas) {
            throw $this->createNotFoundException(
                'There is no data...'
            );
        }

        $jsonContent = $serializer->serialize($dietaDatas, 'json');
        return new Response($jsonContent);
    }
Nayantara Jeyaraj
  • 2,624
  • 7
  • 34
  • 63
Ruslan Poltaev
  • 91
  • 1
  • 1
  • 5
  • You may want to have a look at this one: http://stackoverflow.com/questions/36775899/symfony-3-0-4-circular-reference-detected-during-serialization-with-fosrestbundl , this problem is quite common and also has been documented. – Thai Duong Tran Aug 09 '16 at 10:03

2 Answers2

5

You need to call $normalizer->setCircularReferenceHandler() please read official documentation below:

handling-circular-references

Faraz Partoei
  • 109
  • 1
  • 4
5
 $jsonContent = $serializer->serialize($yourObject, 'json', [
       'circular_reference_handler' => function ($object) {
           return $object->getId();
        }
    ]);

Above Works for me. Hope this will be helpfull (Symfony >=4.2)

Niko Jojo
  • 1,204
  • 2
  • 14
  • 31