Drupal: Creating a Computed Entity Field

0
(0)

An example of creating a calculated field “Age” for materials, which will return the number of seconds elapsed since the node was added. The value will not be stored in the database, but will be calculated the first time it is accessed.

  1. Create field class:
// src/ComputedNodeAgeFieldItemList.php

namespace Drupal\MODULENAME;

use Drupal\Core\Field\FieldItemList;
use Drupal\Core\TypedData\ComputedItemListTrait;
use Drupal\node\NodeInterface;

class ComputedNodeAgeFieldItemList extends FieldItemList {

  use ComputedItemListTrait;

  /**
   * {@inheritdoc}
   */
  protected function computeValue() {
    $node = $this->getEntity(); /** @var NodeInterface $node */
    $node_age = \Drupal::time()->getCurrentTime() - $node->getCreatedTime();
    $this->list[0] = $this->createItem(0, $node_age);
  }

}

2. Add field to nodes:

// MODULENAME.module

use Drupal\computed_field_example\ComputedNodeAgeFieldItemList;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;

/**
 * Implements hook_entity_base_field_info().
 */
function MODULENAME_entity_base_field_info(EntityTypeInterface $entity_type): ?array {
  if ($entity_type->id() == 'node') {
    $fields['age'] = BaseFieldDefinition::create('integer')
      ->setLabel(t('Age'))
      ->setComputed(TRUE)
      ->setClass(ComputedNodeAgeFieldItemList::class)
      ->setReadOnly(TRUE)
      ->setDisplayConfigurable('view', TRUE)
      ->setDisplayOptions('view', [
        'type' => 'number_integer',
      ]);

    return $fields;
  }

  return NULL;
}

3. Clear the cache.

After that, you can access the field in the standard way:

$age = $node->get('age')->value;

Similar Posts:

895

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top