Skip to content

Instantly share code, notes, and snippets.

@opi
Created November 10, 2017 13:27
Show Gist options
  • Select an option

  • Save opi/b3dcfced4e3f7686818c8ac28bbd032a to your computer and use it in GitHub Desktop.

Select an option

Save opi/b3dcfced4e3f7686818c8ac28bbd032a to your computer and use it in GitHub Desktop.
Add a sub token for a node field
<?php
/**
* Implements hook_token_info_alter()
*/
function MODULE_token_info_alter(&$data) {
// Modify description of node tokens for our site.
$data['tokens']['node-field_myfield']['foo'] = [
'name' => "Foo",
'description' => "Process field_myfield value"
];
}
/**
* Implements hook_tokens()
*/
function MODULE_tokens($type, $tokens, array $data, array $options, \Drupal\Core\Render\BubbleableMetadata $bubbleable_metadata) {
// $token_service = \Drupal::token();
$replacements = array();
if ($type == 'node' && !empty($data['node'])) {
$node = $data['node'];
foreach ($tokens as $name => $original) {
switch ($name) {
case 'field_myfield:foo':
if ($node->hasField('field_myfield')) {
// Do your magic foo processing
$replacements[$original] = foo($node->field_episode_order->value);
}
break;
}
}
}
return $replacements;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment