3 namespace Drupal\token\Controller;
5 use Drupal\Component\Serialization\Json;
6 use Drupal\Core\Controller\ControllerBase;
7 use Drupal\token\TreeBuilderInterface;
8 use Symfony\Component\DependencyInjection\ContainerInterface;
9 use Symfony\Component\HttpFoundation\Request;
12 * Returns tree responses for tokens.
14 class TokenTreeController extends ControllerBase {
17 * @var \Drupal\token\TreeBuilderInterface
19 protected $treeBuilder;
21 public function __construct(TreeBuilderInterface $tree_builder) {
22 $this->treeBuilder = $tree_builder;
28 public static function create(ContainerInterface $container) {
30 $container->get('token.tree_builder')
35 * Page callback to output a token tree as an empty page.
37 function outputTree(Request $request) {
38 $options = $request->query->has('options') ? Json::decode($request->query->get('options')) : [];
40 // The option token_types may only be an array OR 'all'. If it is not set,
41 // we assume that only global token types are requested.
42 $token_types = !empty($options['token_types']) ? $options['token_types'] : [];
43 if ($token_types == 'all') {
44 $build = $this->treeBuilder->buildAllRenderable($options);
47 $build = $this->treeBuilder->buildRenderable($token_types, $options);
50 $build['#cache']['contexts'][] = 'url.query_args:options';
51 $build['#title'] = $this->t('Available tokens');
53 // If this is an AJAX/modal request, add a wrapping div to the contents so
54 // that Drupal.behaviors.tokenTree and Drupal.behaviors.tokenAttach can
55 // stil find the elements they need to.
56 // @see https://www.drupal.org/project/token/issues/2994671
57 // @see https://www.drupal.org/node/2940704
58 // @see http://danielnouri.org/notes/2011/03/14/a-jquery-find-that-also-finds-the-root-element/
59 if ($request->isXmlHttpRequest()) {
60 $build['#prefix'] = '<div>';
61 $build['#suffix'] = '</div>';