如何在Symfony2中找不到的实体上转义Twig错误

时间:2014-01-16 17:29:22

标签: symfony doctrine-orm entity twig

当找不到实体时,我正试图逃避树枝错误。

我有一个名为listing的表,它与仓库有关系。如果仓库被删除,那么我在Twig中收到此错误&#34;在渲染模板期间抛出了异常(&#34;未找到实体。&#34;)&#34;。< / p>

我已经尝试了所有这些选项来抑制此错误,但我似乎无法完成任何事情。如果可以的话请帮忙。谢谢!

 {% if inventoryLocation.Warehouse.name is defined %}
 {{ inventoryLocation.Warehouse.name }}
 {% endif %}
 Created this error: "An exception has been thrown during the rendering of a template ("Entity was not found.")"

 {% if inventoryLocation.Warehouse %}
 {{ inventoryLocation.Warehouse.name }}
 {% endif %}
 Created this error: "An exception has been thrown during the rendering of a template ("Entity was not found.")"

 {% if inventoryLocation.Warehouse is not null %}
 {{ inventoryLocation.Warehouse.name }}
 {% endif %}
 Created this error: "An exception has been thrown during the rendering of a template ("Entity was not found.")"

 {% if inventoryLocation.Warehouse sucks because its not there %}
 {{ inventoryLocation.Warehouse.name }}
 {% endif %}
 Doesn't really do anything it just makes me really mad :)

1 个答案:

答案 0 :(得分:0)

我通过在我的实体或正在迭代的实体中创建自定义getter来解决此类问题。

例如 - 在您的情况下 - 您有InventoryLocation和Warehouse。看起来您正在InventoryLocation实体上显示或迭代。

在这种情况下 - 我会在InventoryLocation实体中创建一个看起来像这样的自定义getter:

<?php

public function getWarehouseName()
{
    // Get the associated Warehouse
    if ($this->getWarehouse())
    {
        // Return Warehouse name
        return $this->getWarehouse()->getName();
    }
    else
    {
        return null;
    }
}

然后 - 在您的Twig模板中 - 您可以调用此客户getter方法,并在getter返回NULL时添加默认值。

 {{ inventoryLocation.warehouseName | default('-') }}