Skip to content

Instantly share code, notes, and snippets.

@opi
Created October 21, 2021 12:22
Show Gist options
  • Save opi/cc026d34d402587b6af1b4f14e11f046 to your computer and use it in GitHub Desktop.
Save opi/cc026d34d402587b6af1b4f14e11f046 to your computer and use it in GitHub Desktop.
Computed field example for Drupal 8/9
<?php
// in MY_MODULE/src/ComputedField/BlogAuthorComputed.php
namespace Drupal\MY_MODULE\ComputedField;
use Drupal\Core\Field\EntityReferenceFieldItemList;
use Drupal\Core\TypedData\ComputedItemListTrait;
class BlogAuthorComputed extends EntityReferenceFieldItemList {
use ComputedItemListTrait;
protected function computeValue() {
$delta = 0;
$entity = $this->getEntity();
$this->list[$delta] = $this->createItem($delta, $entity->getOwner()->id());
}
}
<?php
/**
* Implements hook_entity_bundle_field_info().
*/
function MY_MODULE_entity_bundle_field_info(EntityTypeInterface $entity_type, $bundle, array $base_field_definitions) {
$new_definitions = [];
if ($entity_type->id() === 'node') {
if ($bundle == 'blog') {
$new_definitions['blog_author'] = \Drupal\Core\Field\BaseFieldDefinition::create('entity_reference')
->setLabel(t('Author (computed)'))
->setComputed(TRUE)
->setClass('\Drupal\MY_MODULE\ComputedField\BlogAuthorComputed')
->setSettings(array(
'target_type' => 'user',
'default_value' => 0,
))
->setDisplayConfigurable('view', TRUE);
}
}
return $new_definitions;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment