I have a problem with Symfony2 and Twig: I don’t know how to display all fields of my entity which is loaded dynamically. Here is my code (displays nothing!!)
Controller :
public function detailAction($id)
{
$em = $this->container->get('doctrine')->getEntityManager();
$node = 'testEntity'
$Attributes = $em->getRepository('TestBetaBundle:'.$node)->findOneById($id);
return $this->container->get('templating')->renderResponse('TestBetaBundle:test:detail.html.twig',
array(
'attributes' => $Attributes
));
}
detail.html.twig :
{% for key in attributes %}
<p>{{ value }} : {{ key }}</p>
{% endfor %}
OK. What you are trying to do cannot be done with a Twig
forloop over your attributes object. Let me try to explain:The Twig
forloop iterates over an ARRAY of objects, running the inside of the loop for each of the objects in the array. In your case,$attributesis NOT an array, it is an OBJECT which you retrived with yourfindOneByIdcall. So theforloop finds that this is not an array and does not run the inside of the loop, not even once, that is why you get no output.The solution proposed by @thecatontheflat does not work either, as it is just the same iteration over an array, only that you have access to both the keys and values of the array, but since
$attributesis not an array, nothing is accomplished.What you need to do is pass the template an array with the properties of the $Attributes object. You can use the php get_object_vars() function for this. Do something like:
And in the Twig template:
Take into account that this will only show the public properties of your object.