[英]Reading PersistentCollections in Twig as if they were an Array
我在兩個類(協議和歷史)之間存在雙向的一對多關系。 在搜索特定協議時,我希望看到與該協議相關的所有歷史記錄條目。
在渲染模板時,我通過了以下內容:
return $this->render('FunarbeProtocoloAdminBundle:Protocolo:show.html.twig', array(
'entity' => $entity,
'delete_form' => $deleteForm->createView(),
'history' => $entity->getHistory(),
)
);
entity->getHistory()
返回一個PersistentCollection而不是一個數組,這將導致以下錯誤:
{% 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 %}
如果我通過$em->getRepository('MyBundle:History')->findByProtocol($entity)
代替$entity->getHistory()
$em->getRepository('MyBundle:History')->findByProtocol($entity)
,則可以正常工作。 但是我認為具有雙向關系的主要目的是避免打開存儲庫並明確打開新的結果集。
難道我做錯了什么? 我應該怎么做?
我要做的就是在TWIG上調用以下命令:
{% for hist in entity.history %}
沒有其他答案對我有用。 我必須直接在樹枝上調用該屬性,而不是使用其吸氣劑。 不知道為什么,但是有效。
謝謝。
嘗試這個:
return $this->render('FunarbeProtocoloAdminBundle:Protocolo:show.html.twig'
,array(
'entity' => $entity,
,'delete_form' => $deleteForm->createView(),
,'history' => $entity->getHistory()->toArray()
///////////
)
);
您的代碼很好,我總是省去麻煩,把我的收藏放到樹枝上,而不是通過我的視圖傳遞。 您也可以嘗試這個。
渲染代碼變更
return $this->render('FunarbeProtocoloAdminBundle:Protocolo:show.html.twig', array(
'entity' => $entity,
'delete_form' => $deleteForm->createView(),
)
);
您想直接在樹枝中訪問歷史記錄。
枝條
{% 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 %}
如果更改后的結果相同,請嘗試檢查hist是否有數組,它可能是嵌套的! 永久收藏傾向於這樣做...
{% 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 %}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.