I have a bidirectional one-to-many relationship between two classes (Protocol and History). While searching for a specific Protocol, I'm expected to see all History entries associated with that protocol.
While rendering my template, I pass the following:
return $this->render('FunarbeProtocoloAdminBundle:Protocolo:show.html.twig', array(
'entity' => $entity,
'delete_form' => $deleteForm->createView(),
'history' => $entity->getHistory(),
)
);
entity->getHistory()
returns a PersistentCollection instead of an array, which causes the following to render an error:
{% for hist in history %}
<tr>
<td>{{ hist.dtOcorrencia|date('d/m/Y H:i') }}</td>
<td>{{ hist.dtRetorno|date('d/m/Y H:i') }}</td>
</tr>
{% endfor %}
If instead of $entity->getHistory()
I pass $em->getRepository('MyBundle:History')->findByProtocol($entity)
, it works fine. But I figure the main point of having a bidirectional relationship was to avoid opening repositories and explicitly opening new resultsets.
Am I doing something wrong? How am I supposed to do that?
All I had to do was call the following on my TWIG:
{% for hist in entity.history %}
None of the other answers worked for me. I have to call the property directly in my twig instead of using its getter. Don't know why, but it worked.
Thanks.
Try this:
return $this->render('FunarbeProtocoloAdminBundle:Protocolo:show.html.twig'
,array(
'entity' => $entity,
,'delete_form' => $deleteForm->createView(),
,'history' => $entity->getHistory()->toArray()
///////////
)
);
Your code is fine, I always save myself the trouble and get my collections in the twig instead of passing it through my view. You could try this too.
Render code change
return $this->render('FunarbeProtocoloAdminBundle:Protocolo:show.html.twig', array(
'entity' => $entity,
'delete_form' => $deleteForm->createView(),
)
);
You want to access the history directly in your twig.
Twig
{% for hist in entity.getHistory() %}
<tr>
<td>{{ hist.dtOcorrencia|date('d/m/Y H:i') }}</td>
<td>{{ hist.dtRetorno|date('d/m/Y H:i') }}</td>
</tr>
{% endfor %}
If your result after the change is the same, try checking hist for an array, it could be nested! Persistent Collections tend to do that...
{% for history in entity.getHistory() %}
{% for hist in history %}
<tr>
<td>{{ hist.dtOcorrencia|date('d/m/Y H:i') }}</td>
<td>{{ hist.dtRetorno|date('d/m/Y H:i') }}</td>
</tr>
{% endfor %}
{% endfor %}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.