2013-01-07 93 views
2

我在兩個類(Protocol和History)之間有雙向的一對多關係。在搜索特定的協議時,我期望看到與該協議相關的所有歷史條目。在Twig中讀取PersistentCollections,就好像它們是數組一樣

雖然渲染我的模板,我通過了以下內容:

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 %} 

相反,如果$entity->getHistory()我通過$em->getRepository('MyBundle:History')->findByProtocol($entity),它工作正常。但我認爲建立雙向關係的主要目的是避免打開存儲庫並顯式打開新的結果集。

我做錯了什麼?我該怎麼做?

回答

3

我所要做的就是呼籲我的TWIG如下:

{% for hist in entity.history %} 

其他的無答案爲我工作。我必須直接在我的樹枝中調用該屬性,而不是使用它的getter。不知道爲什麼,但它工作。

謝謝。

0

你的代碼沒問題,我總是把自己的麻煩省下來,把我的藏品放在樹枝裏,而不是通過我的視圖。你也可以試試這個。

渲染代碼更改

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 %} 
1

試試這個:

return $this->render('FunarbeProtocoloAdminBundle:Protocolo:show.html.twig' 
    ,array(
      'entity'  => $entity, 
     ,'delete_form' => $deleteForm->createView(), 
     ,'history'  => $entity->getHistory()->toArray() 
               /////////// 
    ) 
); 
相關問題