You are here

public static function PiwikAdminSettingsForm::tokenElementValidate in Piwik Web 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/PiwikAdminSettingsForm.php, line 614

Class

PiwikAdminSettingsForm
Configure Piwik settings for this site.

Namespace

Drupal\piwik\Form

Code

public static function tokenElementValidate(&$element, FormStateInterface $form_state) {
  $value = isset($element['#value']) ? $element['#value'] : $element['#default_value'];
  if (!Unicode::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;
}