如何使用TWIG中的参数访问实体函数 - symfony2

时间:2013-10-29 13:33:14

标签: php symfony doctrine-orm entity twig

我的Symfony2项目中有一个twig模板。 在twig模板中,我有一个实体对象。 此实体对象链接到具有oneToMany关系的另一个实体。

示例:

{{ submission }} -> Submission entity
{{ submission.histories }} -> Histories entity -> I have here an array collection of histories

实体历史记录有一个字段“state_to”

我的目标是只获取state_to为4的历史对象

我试着这样:

{{ submission.histories('status_to', 4)[0] }}

但这不起作用。

我知道我可以使用:

{% for history in submission.histories %}
    {% if history.statusTo == 4 %}
        {{ history.statusDate|date("d F Y") }}
    {% endif %}
{% endfor %}

但我绝对相信有更好的方法。

2 个答案:

答案 0 :(得分:6)

在您的实体中添加方法getHistoryByStatus($status),根据status_to字段过滤您的历史记录,然后在您的模板中:

{% set filtered_history = submission.historyByStatus(4)|default(false) %}
{% if filtered_history %}
    {{ filtered_history.statusDate|date("d F Y") }}
{% endif %}

答案 1 :(得分:2)

你可以在控制器中调用的方法中找到state_to为4的历史对象。然后将其传递给视图。这个方法可以在你的控制器里面,但是最好把它放在你的历史存储库中吗?或经理......

尝试避免视图中的复杂性。

相关问题