簡體   English   中英

你怎么檢查drupal 8中的字段是否為空?

[英]How do you check if a field is empty in drupal 8?

我在基本頁面的內容類型中添加了一個字段。 這是一個選擇框,可以選中或取消選中,具體取決於頁面是否為“入門”類型。 如果頁面是一個入門頁面,我想在html中的body元素中添加“get-started”類,即選中該框。 我想在.theme文件中執行此操作。 所以基本上我想檢查字段是否為空,如果不是將該類添加到body元素。 任何幫助將非常感激。

要檢查字段是否為空,可以使用內置方法isEmpty()

例如:

if (!$entity->get('category')->isEmpty()) {
  /** @var EntityInterface $category */
  $category = $entity->get('category')->entity;
  $row['category']['data'] = [
    '#type' => 'link',
    '#title' => $category->get('name')->value,
    '#url' => $category->toUrl(),
  ];
}
else {
  $row['category'] = NULL;
}

您可以通過以下方式在TWIG模板中檢查該字段是否為空。

{% if node.field_date.value %}
  <div class="my-field-wrapper">
    {{ content.field_date }}
  </div>
{% endif %}

要么

{% if node.field_date.value is not empty %}
  {{ content.field_date }}
{% endif %}

您可以使用template_preprocess_node( https://api.drupal.org/api/drupal/core%21modules%21node%21node.module/function/template_preprocess_node/8 )函數來選擇正在加載的節點的可用變量。

在此功能中,您可以訪問節點的字段,如下所示:

$variables['content']['field_some_name']

如果您的支票通過,您可以添加一些自定義變量以在樹枝模板中使用:

$variables['something'] = true;

或者:您直接在節點樹枝模板中檢查字段的值。 問題是你是否真的有必要將你想要的類添加到body元素中。 也許將它添加到節點的article標簽可以完成工作,這至少更容易檢查。

如果你真的需要將它添加到body元素,我想你需要使用template_preprocess_page函數,並首先檢查正在加載的頁面是否是一個節點,然后找出哪個節點等。

這個解決方案對我field_posterfield_poster沒有或最多1個值。

{% if content.field_poster[0] is not empty %}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM