【问题标题】:How do you check if a form field has data in twig template that is rendering a controller如何检查表单字段中是否有呈现控制器的树枝模板中的数据
【发布时间】:2015-11-23 15:19:24
【问题描述】:

这是this one 的后续问题。我想知道的是如何检查实体变量是否存在/已定义/不为空。我想我可以这样做:

{% if entity.orgId is defined %}
{{ render(controller(
    'CompanyNameofBundle:OrgMember:test', {'orgid':entity.orgId})) }}
{% endif %}

但是,如果 entity.orgId 为 null,我会在呈现模板期间抛出异常(“产品不存在”)。

【问题讨论】:

标签: symfony twig


【解决方案1】:

更改您的控制器以返回 null 而不是异常:

public function testAction($orgid = null) {
    if (!$orgid) { return null; }
// Rest of code.
}

【讨论】:

  • 这就是我一直在寻找的优雅方法! @malcolm
【解决方案2】:

你有两个选择:

  1. 不要使用检查调用渲染控制器

    {% if entity.orgId is defined and entity.orgId is not null %}
    
  2. 使 OrgMemberController 中的 testAction 为空安全(检查参数 orgid 是否为空)

【讨论】:

  • 1) 不工作还是一样 渲染模板时抛出异常(“产品不存在”)。 2)我不能这样做,因为我仍然需要这个对象。渲染控制器需要该参数才能起作用。
【解决方案3】:

试试这个:

{% if entity.orgId is defined %}
    {% if entity.orgId is null %}
        {# do something #}
    {% else %}
        {# do anythingelse #}
    {% endif %}
{% endif %}

【讨论】:

  • 这与上面的答案相同,只是您将其分为两个 for 循环。
  • 有点不同,我用is null代替is not null
  • 这在任何情况下都非常重要,必须在控制器中检查 is 问题,因为由于它从未设置为 null,因此除了错误之外没有返回任何内容。
猜你喜欢
  • 2013-08-07
  • 2019-05-07
  • 1970-01-01
  • 1970-01-01
  • 2020-12-11
  • 1970-01-01
  • 2016-04-30
  • 1970-01-01
  • 2012-11-26
相关资源
最近更新 更多