8

In Drupal 7, you can set defaults values for most fields. Is it possible to set a token as the default value.

I remember this being possible in Drupal 6, but it doesn't seem possible in Drupal 7.

There is a thread here that discuss the possibility, but its not clear if it was solved.

3

3 Answers 3

1

What information do you try to get??

In one of my Content Type, I need to retrieve the node ID. I found that the token for the current node ID is this:

[current-page:url:args:last]

Tested and working for me!!

0

It is working for me:

/**
 * Implements hook_field_widget_form_alter().
 */
function MODULE_hook_field_widget_form_alter(&$element, &$form_state, $context) {
  // Prevent replace tokens on field admin ui form.
  if (!is_null($element['#entity'])) {
    // Determine the $user. If entity has uid, try to load. If can't, use the
    // global $user.
    if (isset($element['#entity']->uid)) {
      if (!$user = user_load($element['#entity']->uid)) {
        global $user;
      }
    }

    // Build data for token replacement.
    $data = array(
      $element['#entity_type'] => $element['#entity'],
      'user' => $user,
    );
    // Eg. the body field, the default value is stored in
    // $element['#default_value']
    if (isset($element['#default_value']) && !is_array($element['#default_value'])) {
      $element['#default_value'] = token_replace($element['#default_value'], $data);
    }
    // Eg. the link field, the default value is stored in
    // $element['#default_value']['url']
    else if (is_array($element['#default_value'])) {
      foreach ($element['#default_value'] as $key => $value) {
        if (is_string($value)) {
          $element['#default_value'][$key] = token_replace($value, $data);
        }
      }
    }
    // Eg. the text field, the default value is stored in
    // $element['value']['#default_value']
    else if (isset($element['value'])) {
      if (isset($element['value']['#default_value']) && !is_array($element['value']['#default_value'])) {
        $element['value']['#default_value'] = token_replace($element['value']['#default_value'], $data);
      }
    }
  }
}
-2

Install the Field default token module.

This module enables to use tokens as field default values. The main discussion: #1070878: Allow tokens to be used in the default value of a field.

1
  • The module doesn't appear to have good support, and there are a number of open issues.
    – mbomb007
    Mar 4, 2019 at 19:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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