Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 - Get an entity instead of PersistentCollection in twig

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...

like image 521
Kaz Avatar asked Jul 09 '14 09:07

Kaz


2 Answers

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

like image 74
Mohamed Ben HEnda Avatar answered Oct 27 '22 01:10

Mohamed Ben HEnda


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 %}
like image 37
Fidan Hakaj Avatar answered Oct 27 '22 01:10

Fidan Hakaj