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

ljolz picture ljolz · Jan 19, 2016 · Viewed 19.7k times · Source

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.

Answer

Onkeltem picture Onkeltem · May 21, 2017

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