Symfony2&树枝:显示所有字段和键

时间:2012-08-02 14:49:48

标签: symfony entity twig

我遇到Symfony2和Twig的问题:我不知道如何显示动态加载的实体的所有字段。这是我的代码(不显示!!)

控制器:

public function detailAction($id)
{
    $em = $this->container->get('doctrine')->getEntityManager();

    $node = 'testEntity'
    $Attributes = $em->getRepository('TestBetaBundle:'.$node)->findOneById($id);

    return $this->container->get('templating')->renderResponse('TestBetaBundle:test:detail.html.twig', 
    array(
    'attributes' => $Attributes
    ));

}

detail.html.twig:

    {% for key in attributes %} 
        <p>{{ value }} : {{ key }}</p>
    {% endfor %}

4 个答案:

答案 0 :(得分:9)

不要只满足于公共财产!获得私人/受保护!

public function detailAction($id){
    $em = $this->container->get('doctrine')->getEntityManager();

    $node = 'testEntity'
    $Attributes = $em->getRepository('TestBetaBundle:'.$node)->findOneById($id);

    // Must be a (FQCN) Fully Qualified ClassName !!!
    $MetaData = $em->getClassMetadata('Test\Beta\Bundle\Entity\'. $node);
    $fields = array();
    foreach ($MetaData->fieldNames as $value) {
        $fields[$value] = $Attributes->{'get'.ucfirst($value)}();
    }

    return $this->container
                ->get('templating')
                ->renderResponse('TestBetaBundle:test:detail.html.twig', 
                array(
                    'attributes' => $fields
                ));

}

答案 1 :(得分:8)

行。在您的属性对象上使用Twig for循环无法完成您要执行的操作。让我试着解释一下:
Twig for循环遍历ARRAY对象,为数组中的每个对象运行循环内部。在您的情况下,$attributes不是数组,它是您通过findOneById调用重新审核的对象。所以for循环发现这不是一个数组,并且不会在循环内部运行,甚至不运行一次,这就是没有输出的原因。 @thecatontheflat提出的解决方案也不起作用,因为它只是对数组的相同迭代,只是你可以访问数组的键和值,但是因为$attributes不是数组,所以没有完成了。

您需要做的是将模板传递给具有$ Attributes对象属性的数组。你可以使用php get_object_vars()函数。做类似的事情:

$properties = get_object_vars ($Attributes);
return $this->container->get('templating')->renderResponse('TestBetaBundle:test:detail.html.twig', 
array(
'attributes' => $Attributes
'properties' => $properties
));

在Twig模板中:

{% for key, value in properties %} 
    <p>{{ value }} : {{ key }}</p>
{% endfor %}

考虑到这只会显示对象的公共属性。

答案 2 :(得分:0)

对于Symfony3

    $em = $this->getDoctrine()->getEntityManager();

    $MetaData = $em->getClassMetadata('TestBetaBundle:Node');
    $fields = $MetaData->getFieldNames();

    return $this->render('test/detail.html.twig', array('fields'=>fields));    

答案 3 :(得分:-2)

您应该将其更改为

{% for key, value in attributes %} 
    <p>{{ value }} : {{ key }}</p>
{% endfor %}