Computed field examples and snippets

Drupal 8 Computed Field snippets

$value = $entity->get('title')->value . ' | ' . $entity->get('body')->value . ' | ' . $entity->field_location->entity->field_address->locality . ', ' . $entity->field_location->entity->field_address->administrative_area . ' | ' . $entity->field_location->entity->get('title')->value . ' | ' .  ($entity->field_is_online->value ? 'Online' : '') . ' | ' . $entity->field_status->entity->name->value;

$value = print_r ($entity->get('body')->value, 'true');
$value =  ($entity->field_is_online->value ? 'Online' : '') ;

 

The following will fail if location is not defined on the node:

$value = $entity->field_location->entity->get('title')->value ;

Fix by changing to

$value = ($entity->field_location->entity ? $entity->field_location->entity->get('title')->value : '');

However, this

$value = $entity->field_status->entity->name->value;

can be fixed with

$value = ($entity->field_status->entity ? $entity->field_status->entity->name->value : '');

but doesn’t have to be.

Test content with computed fields by creating a node and leaving fields blank.