Reputation:
I'm trying to retrieve data from my database with the following code:
$user = $this->get('security.context')->getToken()->getUser();
$pm = $this->getDoctrine()
->getRepository('LoginLoginBundle:Privatemessage')
->findOneByUser_userid($user->getUserid());
Then in my twig file I use this:
{% for i in 0..(pm|length-1)%}
<tr>
<td>{{pm[i].sender}}</td><td></td><td>{{pm[i].subject}}</td>
</tr>
<tr>
<td>{{pm[i].contents()}}</td>
</tr>
{% endfor %}
This fails however, and gives me the following error:
Impossible to access a key "0" on an object of class "Login\LoginBundle\Entity\Privatemessage" that does not implement ArrayAccess interface in LoginLoginBundle:Default:manager.html.twig at line 20
If I use findall(), everything works fine, but then I get all the objects and I just need a few.
Upvotes: 0
Views: 449
Reputation: 13891
findOneBy()
methods are used to query only one instance of your object. It doesn't return a collection through which you can iterate.
In the code you shared you're fetching only one instance of Privatemessage
and you're trying to manipulate it as if it was a collection of private messages. You can't do that.
Your code is working fine when you use findAll()
because findAll()
returns an ArrayCollection of private messages which you can iterate through.
If you want to get only some of your private messages based on any given constraints, you've then to apply filters when querying them.
Upvotes: 2
Reputation: 1480
I guess you want to retrieve all private messages of a given user and display them. In that case you should use findBy*()
instead of findOneBy*()
. The former will return an ArrayCollection
instead of just an instance of PrivateMessage
.
$user = $this->get('security.context')->getToken()->getUser();
$pm = $this->getDoctrine()
->getRepository('LoginLoginBundle:Privatemessage')
->findByUser_userid($user->getUserid());
I also recommend using Twig's for
to iterate through each item of the collection like this:
{% for message in pm %}
<tr>
<td>{{message.sender}}</td><td></td><td>{{message.subject}}</td>
</tr>
<tr>
<td>{{message.contents()}}</td>
</tr>
{% endfor %}
You can read the documentation here.
Upvotes: 1