您如何检查表单字段是否在呈现控制器的树枝模板中包含数据

How do you check if a form field has data in twig template that is rendering a controller

这是 的后续问题。我想知道的是如何检查实体变量 exist/is defined/not 是否为空。我以为我可以做到这一点:

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

但是如果 entity.orgId 为 null,我会在呈现模板 ("The product does not exist") 期间抛出异常。

您有两个选择:

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

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

试试这个:

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

将您的控制器更改为 return null 而不是异常:

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