Posted by eelkeblok on November 20, 2019 at 3:27pm
On a current project we have a requirement to be able to extract token values from an entity that is referring through an entity reference field to a known entity (e.g. the node for the current page). I wrote a module called back reference token (I could not find anything that already does this) and I am considering to contribute it. Does anyone know anything similar like this that I might be stepping on when doing so?

Comments
Good idea
I want to use entity reference from Node A to Node B, and use auto_entitylabel to set Node B's title based on Node A and the reference field delta.
Can your module provide tokens to use in Node B's auto_entitylabel settings?
How do you handle items that have a single reference vs ones that can handle multiple?
Just came across the same
Just came across the same requirements and solved it with this code:
<?php
/<strong>
* Implements hook_token_info().
*/
function generic_extensions_token_info(): array {
$token_info['tokens']['node']['backref'] = [
'name' => t('Back reference'),
'type' => 'node',
];
return $token_info;
}
/</strong>
* Implements hook_tokens().
*/
function generic_extensions_tokens(string $type, array $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata): array {
$replacements = [];
if ($type === 'node' && !empty($data['node'])) {
/** @var \Drupal\node\NodeInterface $node */
$node = $data['node'];
$token_service = \Drupal::token();
if ($backref_tokens = $token_service->findWithPrefix($tokens, 'backref')) {
foreach ($backref_tokens as $backref => $value) {
$parts = explode(':', $backref);
if (count($parts) > 3) {
[$entity_type, $bundle, $field_name, ] = $parts;
/** @var \Drupal\Core\Entity\EntityInterface $backref_entities */
$backref_entities = \Drupal::entityTypeManager()->getStorage($entity_type)->loadByProperties([
'type' => $bundle,
$field_name => $node->id(),
]);
if ($backref_entities) {
$backref_entity = reset($backref_entities);
unset($parts[0], $parts[1], $parts[2]);
$backref_token = [
implode(':', $parts) => $value,
];
$replacements += $token_service->generate('entity', $backref_token, ['entity' => $backref_entity], $options, $bubbleable_metadata);
}
}
}
}
}
return $replacements;
}
?>
This can then be used with a token like
[node:backref:node:article:field_other_node:nid]wherebackref:node:article:field_other_nodedelivers an entity of typenodeand bundlearticlewhich refers back to the calling node from entity reference fieldfield_other_node. The remainder part of the token (here:nid) then refers to that entity that got determined.