/** * Render the token tree for the specified entity. * * @param \Drupal\Core\Entity\EntityInterface $entity * The entity for which the token tree should be rendered. * * @return array * Render array of the token tree for the $entity. * * @see static::entityLoad */ protected function renderTokenTree(EntityInterface $entity) { $this->moduleHandler()->loadInclude('token', 'pages.inc'); $entity_type = $entity->getEntityTypeId(); $token_type = $this->entityMapper->getTokenTypeForEntityType($entity_type); $options = ['flat' => TRUE, 'values' => TRUE, 'data' => [$token_type => $entity]]; $token_tree = [$token_type => ['tokens' => $this->treeBuilder->buildTree($token_type, $options)]]; // foreach ($tree as $token => $token_info) { // if (!isset($token_info['value']) && !empty($token_info['parent']) && !isset($tree[$token_info['parent']]['value'])) { // continue; // } // } $build['tokens'] = ['#type' => 'token_tree_table', '#show_restricted' => FALSE, '#skip_empty_values' => TRUE, '#token_tree' => $token_tree, '#columns' => ['token', 'value'], '#empty' => $this->t('No tokens available.')]; return $build; }
/** * Retrieves suggestions for block category autocompletion. * * @param \Symfony\Component\HttpFoundation\Request $request * The current request. * @param string $token_type * The token type. * @param string $filter * The autocomplete filter. * * @return \Symfony\Component\HttpFoundation\JsonResponse * A JSON response containing autocomplete suggestions. */ public function autocomplete($token_type, $filter, Request $request) { $filter = substr($filter, strrpos($filter, '[')); $matches = array(); if (!Unicode::strlen($filter)) { $matches["[{$token_type}:"] = 0; } else { $depth = max(1, substr_count($filter, ':')); $tree = $this->treeBuilder->buildTree($token_type, ['flat' => TRUE, 'depth' => $depth]); foreach (array_keys($tree) as $token) { if (strpos($token, $filter) === 0) { $matches[$token] = levenshtein($token, $filter); if (isset($tree[$token]['children'])) { $token = rtrim($token, ':]') . ':'; $matches[$token] = levenshtein($token, $filter); } } } } asort($matches); $keys = array_keys($matches); $matches = array_combine($keys, $keys); return new JsonResponse($matches); }