You are here

function field_tokens in Token 7

Same name and namespace in other branches
  1. 8 token.tokens.inc \field_tokens()

Implements hook_tokens() on behalf of field.module.

File

./token.tokens.inc, line 1393
Token callbacks for the token module.

Code

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

  // Entity tokens.
  if ($type == 'entity' && !empty($data['entity_type']) && !empty($data['entity']) && !empty($data['token_type'])) {
    $entity_type = $data['entity_type'];

    // The field API does weird stuff to the entity, so let's clone it.
    $entity = clone $data['entity'];

    // Reset the prepared view flag in case token generation is called from
    // inside field_attach_view().
    unset($entity->_field_view_prepared);
    list(, , $bundle) = entity_extract_ids($entity_type, $entity);
    $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;
      }

      // Replace the [entity:field-name] token only if token module added this
      // token.
      if (isset($tokens[$field_name]) && _token_module($data['token_type'], $field_name) == 'token') {
        $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'][] = 'token_pre_render_field_token';
        $replacements[$original] = drupal_render($field_output);
      }
    }

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