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.
- 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:
- how to Programmatically update an entity reference field in Drupal 8 & 9
- how to set date field programmatically drupal 8 / 9
- Helpful node methods in Drupal 8
- How do I programmatically create a page in drupal 8?
- How to create custom block in Drupal 8 programmatically
895