3 namespace Drupal\views\Plugin\views\area;
5 use Drupal\Core\Form\FormStateInterface;
8 * Tokenized base class for area handlers.
10 * This class provides a method tokenizeValue() to tokenize a given value with
11 * the tokens of the first view result and additionally applies global token
12 * replacement to the passed value. The form elements to enable the replacement
13 * functionality is automatically added to the buildOptionsForm().
15 * @ingroup views_area_handlers
17 abstract class TokenizeAreaPluginBase extends AreaPluginBase {
22 protected function defineOptions() {
23 $options = parent::defineOptions();
24 $options['tokenize'] = ['default' => FALSE];
31 public function buildOptionsForm(&$form, FormStateInterface $form_state) {
32 parent::buildOptionsForm($form, $form_state);
34 // Add tokenization form elements.
35 $this->tokenForm($form, $form_state);
39 * Adds tokenization form elements.
41 public function tokenForm(&$form, FormStateInterface $form_state) {
43 '#type' => 'checkbox',
44 '#title' => $this->t('Use replacement tokens from the first row'),
45 '#default_value' => $this->options['tokenize'],
48 // Get a list of the available fields and arguments for token replacement.
50 $optgroup_arguments = (string) t('Arguments');
51 $optgroup_fields = (string) t('Fields');
52 foreach ($this->view->display_handler->getHandlers('field') as $field => $handler) {
53 $options[$optgroup_fields]["{{ $field }}"] = $handler->adminLabel();
56 foreach ($this->view->display_handler->getHandlers('argument') as $arg => $handler) {
57 $options[$optgroup_arguments]["{{ arguments.$arg }}"] = $this->t('@argument title', ['@argument' => $handler->adminLabel()]);
58 $options[$optgroup_arguments]["{{ raw_arguments.$arg }}"] = $this->t('@argument input', ['@argument' => $handler->adminLabel()]);
61 if (!empty($options)) {
64 '#title' => $this->t('Replacement patterns'),
66 '#id' => 'edit-options-token-help',
69 ':input[name="options[tokenize]"]' => ['checked' => TRUE],
73 $form['tokens']['help'] = [
74 '#markup' => '<p>' . $this->t('The following tokens are available. You may use Twig syntax in this field.') . '</p>',
76 foreach (array_keys($options) as $type) {
77 if (!empty($options[$type])) {
79 foreach ($options[$type] as $key => $value) {
80 $items[] = $key . ' == ' . $value;
82 $form['tokens'][$type]['tokens'] = [
83 '#theme' => 'item_list',
90 $this->globalTokenForm($form, $form_state);
94 * Replaces value with special views tokens and global tokens.
96 * @param string $value
97 * The value to eventually tokenize.
100 * Tokenized value if tokenize option is enabled. In any case global tokens
103 public function tokenizeValue($value) {
104 if ($this->options['tokenize']) {
105 $value = $this->view->getStyle()->tokenizeValue($value, 0);
107 // As we add the globalTokenForm() we also should replace the token here.
108 return $this->globalTokenReplace($value);