You are here

function field_tokens_token_info_alter in Field tokens 8

Same name and namespace in other branches
  1. 7 field_tokens.tokens.inc \field_tokens_token_info_alter()

Implements hook_token_info_alter().

File

./field_tokens.tokens.inc, line 118
Token functions for Field tokens module.

Code

function field_tokens_token_info_alter(&$data) {

  /** @var \Drupal\Core\Entity\EntityTypeBundleInfo $bundle_info */
  $bundle_info = \Drupal::service('entity_type.bundle.info');

  /** @var \Drupal\Core\Entity\EntityFieldManager $entity_field_manager */
  $entity_field_manager = \Drupal::service('entity_field.manager');

  /** @var \Drupal\token\TokenEntityMapper $token_entity_mapper */
  $token_entity_mapper = \Drupal::service('token.entity_mapper');
  $token_entity_map = $token_entity_mapper
    ->getEntityTypeMappings();
  foreach ($token_entity_map as $entity_type => $token_type) {
    if (isset($data['tokens'][$token_type])) {
      $bundles = $bundle_info
        ->getBundleInfo($entity_type);
      foreach (array_keys($bundles) as $bundle) {
        try {
          $fields = $entity_field_manager
            ->getFieldDefinitions($entity_type, $bundle);
          foreach ($fields as $field_name => $field) {
            if ($field instanceof FieldConfig && isset($data['tokens'][$token_type][$field_name])) {

              // Formatted field tokens.
              $data['tokens'][$token_type]["{$field_name}-formatted"] = [
                'name' => t('@label: Formatted field', [
                  '@label' => $field
                    ->label(),
                ]),
                'description' => t("The formatted value of one or more @label field values. Replace '?' with a comma seperated list of deltas (e.g., '0,1').", [
                  '@label' => $field
                    ->label(),
                ]),
                'type' => "formatted_field-{$field->getType()}",
                'dynamic' => TRUE,
              ];

              // Field property tokens.
              $data['tokens'][$token_type]["{$field_name}-property"] = [
                'name' => t('@label: Field properties', [
                  '@label' => $field
                    ->label(),
                ]),
                'description' => t("Field properties from one or more @label field values. Replace '?' with a comma seperated list of deltas (e.g., '0,1').", [
                  '@label' => $field
                    ->label(),
                ]),
                'type' => "field_property-{$field->getType()}",
                'dynamic' => TRUE,
              ];
            }
          }
        } catch (Exception $e) {

          // @TODO - Find a better way to prevent errors when loading field
          // definitions.
        }
      }
    }
  }
}