You are here

function field_default_token_default_value_callback in Field default token 8

Default value callback for fields with default values containing tokens.

Parameters

\Drupal\Core\Entity\FieldableEntityInterface $entity: The entity being created.

\Drupal\Core\Field\FieldDefinitionInterface $definition: The field definition.

Return value

array[] A numerically indexed array of items, each item being an associative array where the keys are the property names and the values the respective property values.

5 string references to 'field_default_token_default_value_callback'
FieldDefaultTokenBasicTest::testCallbackExistingField in tests/src/Kernel/FieldDefaultTokenBasicTest.php
Tests that the default value callback is registered for an existing field.
FieldDefaultTokenBasicTest::testCallbackNewField in tests/src/Kernel/FieldDefaultTokenBasicTest.php
Tests that the default value callback is registered for a new field.
FieldDefaultTokenBasicTest::testCallbackRemoval in tests/src/Kernel/FieldDefaultTokenBasicTest.php
Tests the the default value callback is removed properly.
field_default_token_field_config_presave in ./field_default_token.module
Implements hook_ENTITY_TYPE_presave() for field configuration.
field_default_token_form_field_config_edit_form_alter in ./field_default_token.module
Implements hook_form_FORM_ID_alter() for the field configuration edit form.

File

./field_default_token.module, line 59
Enables to use tokens as field default values.

Code

function field_default_token_default_value_callback(FieldableEntityInterface $entity, FieldDefinitionInterface $definition) {
  $entity_type = $entity
    ->getEntityType();
  $token_type = $entity_type
    ->get('token_type') ?: $entity_type
    ->id();
  $data = !$entity
    ->isNew() ? [
    $token_type => $entity,
  ] : [];
  $allowed_values = $definition
    ->getSetting('allowed_values');
  $token_is_label = $allowed_values && $definition instanceof FieldConfigInterface && $definition
    ->getThirdPartySetting('field_default_token', 'label_token', FALSE);

  /** @var \Drupal\Core\Utility\Token $token */
  $token = \Drupal::service('token');
  $items = $definition
    ->getDefaultValueLiteral();
  foreach ($items as &$item) {
    foreach ($item as $property_name => $property_value) {
      if (is_array($property_value)) {
        continue;
      }
      $item[$property_name] = $token
        ->replace($property_value, $data, [
        'clear' => TRUE,
      ]);
      if ($token_is_label) {
        $item[$property_name] = array_search($item[$property_name], $allowed_values);
      }
    }
  }
  return $items;
}