Domanda

In my_module I have the following:

function my_module_token_info()
{
  $info = [];
  $info['types']['my_module_tokens'] = [
      'name' => 'My Module Tokens',
      'description' => t('Tokens specific to my module.'),
  ];
  $info['tokens']['my_module_tokens']['my_token'][] = 'For my token in a node body';

  return $info;
}

function my_module_tokens($type, $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata) {
  $replacements = [];

  if ($type == 'my_module_tokens') {
    foreach ($tokens as $name => $original) {
      switch ($name) {
        case 'my_token':
          $replacements[$original] = 'test';
          break;

        default:
          break;
      }
    }
  }

  return $replacements;
}

In a node body I have [my_module_tokens:my_token]

Now, the token info is found and processed, and appears in the token list. The implementation of hook_tokens does not fire unless I add the following:

function my_module_preprocess_node(&$variables) {
  $token = Drupal::token();
  $token->replace("[my_module_tokens:my_token]", array('node'=>$variables['node']), array('clear' => TRUE));
  }
}

The token information and replacement text are sent off to the tokens logic, but the result is that the token in the body text is unchanged.

È stato utile?

Soluzione

You need to add a way to process the token. The Token Filter module provides a ckeditor filter plugin to do this when the field is rendered.

From the module's README:

Install the module as any other module. Visit the text format administration page at /admin/config/content/formats/filters and edit a text format. Check the 'Replaces global tokens with their value' filter and save the text format.

When editing a form where this text format is used in a field, you can type global tokens that will be replaced when the field is rendered.

Altri suggerimenti

Ah, got it. I had my brain in backwards. Token replacement is on node save, not when it's rendered. Calling token replace in hook_node_presave did it.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a drupal.stackexchange
scroll top