Problem/Motivation
Computed fields are currently not available as Tokens. This may be a simple oversight as it seems like something that should be supported?
I can't see how it would be that different to replacing a basic field providing it's class extends FieldItemList.
Steps to reproduce
1. Create a custom content entity with a simple computed field
/**
* {@inheritdoc}
*/
public static function baseFieldDefinitions(EntityTypeInterface $entity_type): array {
$fields = parent::baseFieldDefinitions($entity_type);
// Add a field that shows a link to the user's current company.
$fields['label'] = BaseFieldDefinition::create('string')
->setName('label')
->setLabel(t('Label'))
->setComputed(TRUE)
->setReadOnly(TRUE)
->setClass(LabelComputedField::class)
->setDisplayConfigurable('view', TRUE)
->setDisplayOptions('view', [
'label' => 'hidden',
'weight' => -5,
]);
return $fields;
}
/**
* Label computed field class.
*/
class LabelComputedField extends FieldItemList {
use ComputedItemListTrait;
/**
* Computes the values for an item list.
*/
protected function computeValue() {
/** @var \Drupal\Core\Field\FieldItemInterface $item */
$item = $this->createItem(0, 'My Amazing Label');
$this->list[0] = $item;
}
}
2. View available tokens. The computed field is not available.
Proposed resolution
The code in token.tokens.inc currently calls EntityFieldManager::getFieldStorageDefinitions():
$fields = \Drupal::service('entity_field.manager')->getFieldStorageDefinitions($entity_type_id);
Where this code deliberately ignores Computed fields:
foreach ($this->getBaseFieldDefinitions($entity_type_id) as $field_name => $definition) {
if (!$definition->isComputed()) {
$this->fieldStorageDefinitions[$entity_type_id][$field_name] = $definition;
}
}
So either:
1. Create a way of retrieving fields, including computed definitions, from via `EntityFieldManager` either as an additional arg or new method
2. Rework _field_token_info_alter() to also separately fetch and merge in computed fields
Remaining tasks
1. Decide on best solution
2. Implement
3. Add tests
Comments
Comment #2
mattjones86This could also possibly just be fixed in contrib:
Comment #3
quietone commentedIn Drupal core changes are made on on 11.x (our main development branch) first, and are then back ported as needed according to the Core change policies. Thanks.