2013-11-02 99 views
0

我想通過樹枝中的對象迭代,但我沒有這樣的運氣。這是迄今爲止我嘗試過的。迭代通過樹枝中的循環

這裏是我的默認控制器方法:

public function ReturnPhonesAction() 
    { 
     $phonequery = $this->getDoctrine() 
     ->getRepository('TravelTravelBundle:Phone') 
     ->findAll(); 

     if($phonequery != NULL) { 

      return $this->render('TravelTravelBundle:Default:returnphone.html.twig', 
       array('attributes' => $phonequery) 
      );   
     } 
    } 

我的枝杈:

{% extends 'TravelTravelBundle::base.html.twig' %} 
{% block title %}Return Phone{% endblock %} 
{% block body %}  
    {% for key, attribute in attributes %} 
     {% if attribute is not empty %} 
      <div class="{{ key }}"> 
       {{ key|capitalize }}:&nbsp;{{ attribute }}<br /><br /> 
      </div> 
     {% endif %} 
    {% endfor %} 
{% endblock %} 

這裏的$phonequery的var_dump:

array(2) 
{ 
    [0]=> object(Travel\Bundle\TravelBundle\Entity\Phone)#264 (4) { 
     ["id":"Travel\Bundle\TravelBundle\Entity\Phone":private]=> int(4) 
     ["name":"Travel\Bundle\TravelBundle\Entity\Phone":private]=> string(4) "dave" 
     ["phone":"Travel\Bundle\TravelBundle\Entity\Phone":private]=> string(13) "(801)850-1531" 
     ["email":"Travel\Bundle\TravelBundle\Entity\Phone":private]=> string(0) "" } 

     [1]=> object(Travel\Bundle\TravelBundle\Entity\Phone)#265 (4) { 
      ["id":"Travel\Bundle\TravelBundle\Entity\Phone":private]=> int(5) 
      ["name":"Travel\Bundle\TravelBundle\Entity\Phone":private]=> string(5) "Brian" 
      ["phone":"Travel\Bundle\TravelBundle\Entity\Phone":private]=> string(10) "8018952364" 
      ["email":"Travel\Bundle\TravelBundle\Entity\Phone":private]=> string(13) "[email protected]" 
     } 
} 

我不斷收到此錯誤:Catchable fatal error: Object of class Travel\Bundle\TravelBundle\Entity\Phone could not be converted to string

我在這裏做錯了什麼?當通過教義的->findBy查詢屬性數組的值內的單行時,它似乎工作正常。當我通過教條的->findAll();從mysql查詢所有行時,返回的對象破壞了我的樹枝。什麼需要改變?

回答

1

您正在遍歷包含對象的數組。然後你打印鍵和對象。這意味着您嘗試將對象轉換爲字符串。

{# key is string, attribute is the object #} 
{% for key, attribute in attributes %} 
    {% if attribute is not empty %} 
     <div class="{{ key }}"> 
            {# attribute is still an object, you cannot print it #} 
      {{ key|capitalize }}:&nbsp;{{ attribute }}<br /><br /> 
     </div> 
    {% endif %} 
{% endfor %} 
0

這正是錯誤消息所說的:您無法打印對象。
在您的模型上執行__toString()方法,或者訪問對象的屬性,如
{{ attribute.name }}