2

I have created a custom token. Inside my token's code, I'm getting a node object. I want to give the users the option of displaying this node's properties. So, for example, assuming that my token's name is [mycustomtoken] I want them to be able to write:

[mycustomtoken:author] so that they get the node's author or

[mycustomtoken:title] to get the node's title.

Is there a way to do this in Drupal?

1

Yes, by making your token a dynamic token in HOOK_token_info() and using the provided name during HOOK_tokens() to dynamically create your replacements.

Example

function HOOK_token_info() {
  ...

  $tokens['mycustomtoken'] = array(
     ...
     'dynamic' => TRUE,
  );

  ...
}

function HOOK_tokens($type, $tokens, array $data = array(), array $options = array()) {
  ...

  if ($type == 'mycustomtoken' && !empty($data['node'])) {
    $node = $data['node'];

    foreach ($tokens as $name => $original) {
      if (isset($node->{$name})) {
        $replacements[$original] = $node->{$name};
      }
    }
  }

  ...
}
| improve this answer | |
0

Check this code:

function MODULE_NAME_tokens($type, $tokens, array $data = array(), array $options = array()) {
    $replacements = array();
    $sanitize = !empty($options['sanitize']);

    if ($type == 'node' && !empty($data['node'])) {
        $node = $data['node'];

        foreach ($tokens as $name => $original) {
            switch ($name) {
                case 'pathauto':
                    $replacements[$original] = str_replace(
                            array('&', '&'),
                            'and',
                            $sanitize ? filter_xss($node->title) : $node->title
                    );
                    break;
            }
        }
    }

    return $replacements;
}
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy