You are here

public static function MatomoAdminSettingsForm::tokenElementValidate in Matomo Analytics 8

Validate a form element that should have tokens in it.

For example:

$form['my_node_text_element'] = [
  '#type' => 'textfield',
  '#title' => $this
    ->t('Some text to token-ize that has a node context.'),
  '#default_value' => 'The title of this node is [node:title].',
  '#element_validate' => [
    [
      get_class($this),
      'tokenElementValidate',
    ],
  ],
];

File

src/Form/MatomoAdminSettingsForm.php, line 703

Class

MatomoAdminSettingsForm
Configure Matomo settings for this site.

Namespace

Drupal\matomo\Form

Code

public static function tokenElementValidate(&$element, FormStateInterface $form_state) {
  $value = isset($element['#value']) ? $element['#value'] : $element['#default_value'];
  if (!mb_strlen($value)) {

    // Empty value needs no further validation since the element should depend
    // on using the '#required' FAPI property.
    return $element;
  }
  $tokens = \Drupal::token()
    ->scan($value);
  $invalid_tokens = static::getForbiddenTokens($tokens);
  if ($invalid_tokens) {
    $form_state
      ->setError($element, t('The %element-title is using the following forbidden tokens with personal identifying information: @invalid-tokens.', [
      '%element-title' => $element['#title'],
      '@invalid-tokens' => implode(', ', $invalid_tokens),
    ]));
  }
  return $element;
}