Simon Delaunay
Simon Delaunay

Reputation: 145

Symfony2 OneToMany relation

Related to my previous post :

Symfony2 OneToMany relation

I wanna add this feature to my infoAction(); who list all the adverts.

    public function infoAction()
{
    $listAdverts = $this->getDoctrine()
        ->getManager()
        ->getRepository('SocietyPerfclientBundle:Advert')
        ->getAdverts()
    ;

    return $this->render('SocietyPerfclientBundle:Default:info.html.twig', array(
        'listAdverts' => $listAdverts,
    ));
}

What i have to do here to access in my view :

{% for reader in advert.readers %} <i>Seen by : {{ reader.username }}</i> {% endfor %}

Upvotes: 0

Views: 95

Answers (2)

Dan Costinel
Dan Costinel

Reputation: 1736

First of all, regarding your first link (which, from now on, you should post all the problems/question in one single post, and not creating multiple ones, and if you have something to add/remove, you can edit your post), you are not setting the relation correctly:

In class Advert you are missing some essential methods. For that, run

$ php app/console doctrine:generate:entities SocietyPerfclientBundle:Advert

to let doctrine generate the missing methods for you. Same for AdvertReader entity.

At the end, you have to have the instantiation for $readers field in Advert entity. Something like:

$this->readers = new \Doctrine\Common\Collections\ArrayCollection();

And as well as these methods: addReader(AdvertReader $reader), removeReader(AdvertReader $reader), and getReaders().

In AdvertReader entity, you only have to have setAdvert(Advert $advers) and getAdvert().

Give it a try and let us know if worked or not.

Upvotes: 1

slig36
slig36

Reputation: 185

You give to your template $listAdvert whose contains your advert data. In order to display it in your view you have to use it not directly the name of your Entity

{% for reader in listAdverts.readers %}
    <i>Seen by : {{ reader.username }}</i>
 {% endfor %}

Fixing Controller

$listAdverts = $this->getDoctrine()
        ->getManager()
        ->getRepository('SocietyPerfclientBundle:Advert')
        ->findAll()
    ;

Upvotes: 0

Related Questions