I have this two entities in my project
class PoliceGroupe
{
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="code", type="string", length=50)
*/
private $code;
/**
* @ORM\ManyToMany(targetEntity="PointVente", inversedBy="policegroupe")
* @ORM\JoinTable(name="police_groupe_point_vente",
* joinColumns={@ORM\JoinColumn(name="police_groupe_id", referencedColumnName="id")},
* inverseJoinColumns={@ORM\JoinColumn(name="point_vente_id", referencedColumnName="id")}
* )
*/
private $pointVente;
/**
* Constructor
*/
public function __construct($produit)
{
$this->pointVente = new \Doctrine\Common\Collections\ArrayCollection();
}
}
And here is my other entity
class PointVente
{
/**
* @var string
*
* @ORM\Column(name="abb", type="string", length=50)
*/
private $abb;
/**
* @var string
*
* @ORM\Column(name="libelle", type="string", length=255)
*/
private $libelle;
/**
*
* @ORM\ManyToMany(targetEntity="PoliceGroupe", mappedBy="pointVente")
*/
private $policegroupe;
}
and i'm trying to run this code in my controller
$encoders = array(new XmlEncoder(), new JsonEncoder());
$normalizers = array(new ObjectNormalizer());
$serializer = new Serializer($normalizers, $encoders);
$em = $this->getDoctrine()->getManager();
$data = $request->get('data');
$policegroupe=$em->getRepository('StatBundle:PoliceGroupe')->findOneBy(array('id' => $data));
$pointventes = $policegroupe->getPointVente();
$jsonContent = $serializer->serialize($pointventes, 'json');
return new JsonResponse( array('pointventes'=>$jsonContent) );
But I get this exception
Symfony\Component\Serializer\Exception\CircularReferenceException: A circular reference has been detected (configured limit: 1).
at n/a
in C:\wamp\www\Sys\vendor\symfony\symfony\src\Symfony\Component\Serializer\Normalizer\AbstractNormalizer.php line 194
I mapped my entities according to the doctrine annotations. Am I missing something?
Symfony 3.2
Use the
useCircularReferenceLimit
method. For example:The reason is that the circular referencing in your entities causes some problems when you try to serialize them. The effect of the method is to define the maximum depth of the serialization hierarchy.
Edit: Added circular reference handler (A circular reference has been detected (configured limit: 1) Serializer SYMFONY)
EDIT : Update (Symfony 4.2)
To be tried with Symfony 3.2, but the
circular_reference_limit
is not the problem here (and the defaults to 1 is OK, else your entity will be retrieved 2 times), the problem is the way the entity is handled bycircular_reference_handler
. Telling thatid
is the entity identifier solves the problem. See Symfony Docs at the bottom of this paragraph.Since
setCircularReferenceHandler
is deprecated in favour of the following keys of the contextcircular_reference_handler
, we can write:Fixed same issue by
Read here