0

I'm trying to add a token to Product using the below code. The problem is that, although this adds the token I'm after, it also removes a number of standard tokens that are needed (e.g., the title).

/**
 * Implements hook_token_info().
 */
function fw_product_token_info() {

  $type = [
    'name' => 'Product',
    'description' => t('Useful additional tokens for products'),
    'needs-data' => 'commerce_product',
  ];

  $tokens['fw_product_parent_url'] = [
      'name' => t('Parent URL'),
      'description' => t('The full path to this product\'s parent'),
  ];

  return [
    'types' => ['commerce_product' => $type],
    'tokens' => ['commerce_product' => $tokens],
  ];

}

/**
 * Implements hook_tokens().
 */
function fw_product_tokens($type, $tokens, array $data = [], array $options = [], BubbleableMetadata $bubbleable_metadata) {

  $replacements = [];

  if ($type == 'commerce_product' && !empty($data['commerce_product'])) {
    foreach ($tokens as $name => $original) {
      switch ($name) {
        case 'fw_product_parent_url':
          $entity = $data['commerce_product'];
          if ($parent_entity = \Drupal::service('fw_product.parent')->getEntity($entity)) {
            $replacements[$original] = $parent_entity->url('canonical');
          }
          else {
            $replacements[$original] = '';
          }
          break;
      }
    }
  }
  return $replacements;
}
2

Return 'tokens' if you want to add new/custom to the existing list.

return [
  'tokens' => ['commerce_product' => $tokens],
];
1

That's because you are not just defining the token but also the token type. Don't define that if it's not yours to define.

To prevent conflicts, token module only defines tokens for base fields if there are no default token types for a given entity type.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.