I'm receiving a list of elements from an API. All the elements are well formatted. When I dump one of them using twig, I get the following :
Leg {#2695 ▼
-id: null
#reservation: null
-airportStart: "AIX LES MILLES"
-airplaneType: "Cessna Citation Mustang"
-airportEnd: "ROBINSON"
-startDate: "2015-09-10 20:00:00"
-startHour: "2015-09-10 20:00:00"
-endHour: "2015-09-10 21:00:21"
-durationLeg: "01:21"
#nbPax: "4"
-price: null
-updatedPrice: null
-discountOnLeg: null
-tva: null
-status: null
}
My user must select one of these elements, So what I'm trying to do is to send the encoded json back to the controller, using
{{ element|json_encode }}
Unfortunately, the json is empty. When I try to dump the encoded json using
{{ dump(element|json_encode) }}
all I get is an empty array {};
Any idea why Is there another way to send the selected element datas to a controller function? (These elements are not persisted, each call on the API returns thousands of results)
I'm little late to the party (2 years of lateness), but for any one like me coming from a google research i say : i had the same problem too, and after googling around, i "solved" my problem with the Serializer Component. How? let me show you!
Installation
php composer.phar require symfony/serializer
Entity
<?php
namespace Your\Namespace\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
/**
* Leg
*
* @ORM\Table()
* @ORM\Entity(repositoryClass="Your\Namespace\Entity\LegRepository")
*/
class Leg {
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
...
public function serializer()
{
$encoder = new JsonEncoder();
$normalizer = new ObjectNormalizer();
$normalizer->setIgnoredAttributes(array(
'whatever', 'attributes', 'you', 'want', 'to', 'ignore'
));
// The setCircularReferenceLimit() method of this normalizer sets the number
// of times it will serialize the same object
// before considering it a circular reference. Its default value is 1.
$normalizer->setCircularReferenceHandler(function ($object) {
return $object->getName();
});
$serializer = new Serializer(array($normalizer), array($encoder));
return $serializer->serialize($this, 'json');
}
}
Twig
{{ Leg.serializer|raw }}
N.B : this is tested under symfony 2.6