I'm using symfony2, and I can't manage to get my related entity in twig.
So I have my main entity, let's call it Post, which has a OneToMany relation :
/**
* @ORM\OneToMany(targetEntity="Comment", mappedBy="Post", cascade={"persist", "remove"})
*/
private $comments;
And I'm passing it to twig with my controller, I can access every property, but when I try to access a property with relations like "Comment", i'm getting a "Doctrine\ORM\PersistentCollection)" which has a lot of private property, and I can't manage to get the properties of this related entity...
I'm a little confused, and I don't know what I'm doing wrong...
Get First item of the doctrine collection in twig
if you have only 1 object on the collection then you can get it by using the first
method
{% set comment = post.comments.first %}
PersistentCollection: first() method
Convert DoctrineCollection to array in twig
To convert the doctrine collection to an array you can use the getValues() method :
{% set arrayComment = post.comments.getValues %}
PersistentCollection: getValues() method
It's because you are trying to access a collection of entities directly. You have to loop your comments collection :
{% for comment in post.comments %}
// You can get your comment entity here
// for example
<p>{{comment.description}}</p>
{% endfor %}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With