Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 717
ljolz Avatar asked Jan 19 '16 06:01

ljolz


3 Answers

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;
}
like image 108
Onkeltem Avatar answered Nov 08 '22 11:11

Onkeltem


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

{% if content.field_poster[0] is not empty %}
like image 39
illutek Avatar answered Nov 08 '22 12:11

illutek


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 %}
like image 3
manikandan k Avatar answered Nov 08 '22 13:11

manikandan k