/** * Page callback to output a token tree as an empty page. */ function outputTree(Request $request) { $options = $request->query->has('options') ? Json::decode($request->query->get('options')) : []; // The option token_types may only be an array OR 'all'. If it is not set, // we assume that only global token types are requested. $token_types = !empty($options['token_types']) ? $options['token_types'] : []; if ($token_types == 'all') { $build = $this->treeBuilder->buildAllRenderable($options); } else { $build = $this->treeBuilder->buildRenderable($token_types, $options); } $build['#cache']['contexts'][] = 'url.query_args:options'; $build['#title'] = $this->t('Available tokens'); return $build; }
/** * 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); }