1.20.x field.tokens.inc field_tokens($type, $tokens, array $data = array(), array $options = array())

Implements hook_tokens().

File

modules/field/field.tokens.inc, line 46
Builds placeholder replacement tokens for field-related data.

Code

function field_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $replacements = array();
  $sanitize = !empty($options['sanitize']);
  $langcode = isset($options['language']) ? $options['language']->langcode : NULL;

  // Entity tokens.
  if (!empty($data[$type]) && is_a($data[$type], 'Entity')) {
    // The field API does weird stuff to the entity, so let's clone it.
    $entity = clone $data[$type];
    $entity_type = $entity->entityType();
    $bundle = $entity->bundle();

    // Reset the prepared view flag in case token generation is called from
    // inside field_attach_view().
    if (isset($entity->_field_view_prepared)) {
      unset($entity->_field_view_prepared);
    }

    $fields = field_info_instances($entity_type, $bundle);
    foreach (array_keys($fields) as $field_name) {
      // Do not continue if the field is empty.
      if (empty($entity->{$field_name})) {
        continue;
      }

      // Node module already replaces the body field as [node:body].
      if ($entity_type == 'node' && $field_name == 'body') {
        continue;
      }

      if (isset($tokens[$field_name])) {
        $original = $tokens[$field_name];

        $field_output = field_view_field($entity_type, $entity, $field_name, 'token', $langcode);
        $field_output['#token_options'] = $options;
        $field_output['#pre_render'][] = 'field_pre_render_token';
        $replacements[$original] = backdrop_render($field_output);
      }
    }

    // Remove the cloned object from memory.
    unset($entity);
  }

  return $replacements;
}