0

我正在尝试遍历 Twig 中的对象,但没有这样的运气。这是我到目前为止所尝试的。

这是我的默认控制器方法:

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

这是$phonequeryvar_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) "dave@dave.com" 
       }
}

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

我在这里做错了什么?通过教义查询属性数组值内的单行时,它似乎工作正常->findBy。当我通过学说从 mysql 查询所有行时,->findAll();返回的对象正在破坏我的树枝。需要改变什么?

4

2 回答 2

0

您正在使用对象遍历数组。然后打印密钥和对象。这意味着您尝试将对象转换为字符串。

{# 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 %}
于 2013-11-02T08:27:04.020 回答
0

这正是错误消息所说的:您无法打印该对象。
要么在模型上实现__toString()方法,要么访问对象的属性,如
{{ attribute.name }}.

于 2013-11-02T08:29:49.750 回答