When I pass the variable from twig to javascript, and display it in the console it returns an empty object.
The controller that sends variable $user to twig
$user = $userRepository->findAll();
$hall = $hallRepository->findAll();
return $this->render('pages/leader_hall/home.html.twig', [
'leadersHall' => $leadersHall,
'user'=> $user,
'hall' => $hall
]);
Here is the twig dump which sends me the data correctly(The data is correctly sent and completed
"user" => array:7 [▼
0 => App\Entity\User {#783 ▶}
1 => App\Entity\User {#615 ▶}
2 => App\Entity\User {#655 ▶}
3 => App\Entity\User {#392 ▶}
4 => App\Entity\User {#796 ▶}
5 => App\Entity\User {#602 ▶}
6 => App\Entity\User {#608 ▶}
]
The javascript code to retrieve the variable User
var user = JSON.parse('{{ user | json_encode| raw}}')
console.log(user)
the returned log (an array containing an empty object)
[
{},
{},
{},
{},
{},
{},
{}
]
Thanks for your help
CodePudding user response:
The problem is solved, it was necessary to serialize $user in the controller
$user = $userRepository->findAll();
$hall = $hallRepository->findAll();
$encoder = new JsonEncoder();
$defaultContext = [
AbstractNormalizer::CIRCULAR_REFERENCE_HANDLER => function ($object, $format, $context) {
return $object->getName();
},
];
$normalizer = new ObjectNormalizer(null, null, null, null, null, null, $defaultContext);
$serializer = new Serializer([$normalizer], [$encoder]);
$userSerialze = $serializer->serialize($user, 'json');
return $this->render('pages/leader_hall/home.html.twig', [
'leadersHall' => $leadersHall,
'hall' => $hall,
'user' => $userSerialze
]);