You are here

public static function BackgroundImageFormTrait::addTokenBrowser in Background Image 2.0.x

Same name and namespace in other branches
  1. 8 src/BackgroundImageFormTrait.php \Drupal\background_image\BackgroundImageFormTrait::addTokenBrowser()
  2. 2.x src/BackgroundImageFormTrait.php \Drupal\background_image\BackgroundImageFormTrait::addTokenBrowser()

Adds a "Browse available tokens" link to the specified element.

Note: this requires the "token" contrib module for it to actually work.

Parameters

array $element: The render array element to attach the token link to.

string|string[]|\Drupal\Core\Entity\EntityInterface $tokenTypes: The token types to display. If not set, all enabled entity types will be used.

1 call to BackgroundImageFormTrait::addTokenBrowser()
BackgroundImageForm::buildSettings in src/Form/BackgroundImageForm.php
Builds the "Settings" group.

File

src/BackgroundImageFormTrait.php, line 111

Class

BackgroundImageFormTrait
Trait BackgroundImageFormTrait.

Namespace

Drupal\background_image

Code

public static function addTokenBrowser(array &$element, $tokenTypes = NULL) {
  if ($tokenEntityMapper = self::getTokenEntityMapper()) {
    if ($tokenTypes instanceof EntityInterface) {
      $tokenTypes = [
        $tokenTypes
          ->getEntityTypeId(),
      ];
    }
    elseif (!isset($tokenTypes)) {
      $tokenTypes = array_keys(self::getBackgroundImageManager()
        ->getEnabledEntityTypes());
    }

    // Map appropriate token types values.
    $tokenTypes = array_map(function ($tokenType) use ($tokenEntityMapper) {
      return $tokenEntityMapper
        ->getTokenTypeForEntityType($tokenType) ?: $tokenEntityMapper
        ->getEntityTypeForTokenType($tokenType, $tokenType);
    }, array_merge([
      'background_image',
    ], (array) $tokenTypes));
    $element['token'] = [
      '#theme' => 'token_tree_link',
      '#token_types' => $tokenTypes,
      '#global_types' => TRUE,
      '#dialog' => TRUE,
    ];
  }
  else {
    $element['token']['#markup'] = t('To browse available tokens, install the @token module.', [
      '@token' => Link::fromTextAndUrl('Token', Url::fromUri('https://www.drupal.org/project/token', [
        'attributes' => [
          'target' => '_blank',
        ],
      ]))
        ->toString(),
    ]);
  }
}