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

25,952

Solution 1

To check if a field is empty you can use built-in method isEmpty().

E.g.:

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;
}

Solution 2

The following way you can check the field is empty or not in TWIG template.

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

or

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

Solution 3

This solution worked for me, the field_poster has none or max 1 value.

{% if content.field_poster[0] is not empty %}
Share:
25,952
ljolz
Author by

ljolz

Updated on July 05, 2022

Comments

  • ljolz
    ljolz almost 2 years

    I have a field added to the content type of basic page. It is a select box, which is either checked or unchecked depending on whether or not the page is of the 'getting started' kind. I want to add the class 'getting-started' to the body element in the html if the page is a getting started page, i.e. the box is checked. I want to do this in the .theme file. So essentially I want to check too see if the field is empty, and if it isn't add the class to the body element. Any help would be much appreciated.

  • ljolz
    ljolz over 8 years
    Unfortunately I do have to add the class to the body element, since I need to change the color of the page title depending on the value of the field I'm checking. I'm familiar with the process of adding a class to the body in the 'template_preprocess_page' function, but I'm not familiar with the how's and why's of what you described in the latter part of your response, "check first if the page being loaded is a node and then find out which node etc".
  • ljolz
    ljolz over 8 years
    Couldn't I just check to see if the field isset with the code you sampled above, and then apply the class all in the preprocess page function?
  • Frank Drebin
    Frank Drebin over 8 years
    The "problem" is that template_preprocess_page is being called on all pages, not only nodes, e.g. on category pages, the front page or any other custom entity pages. So the $variables variable is not always the same. That's what I meant with "check first if the page being loaded is a node, and then find out which node etc.".
  • Dalin
    Dalin over 3 years
    This will only work if this field type has a "value" property. Most don't.