You are here

public static function GoogleAnalyticsAdminSettingsForm::tokenElementValidate in Google Analytics 8.2

Same name and namespace in other branches
  1. 8.3 src/Form/GoogleAnalyticsAdminSettingsForm.php \Drupal\google_analytics\Form\GoogleAnalyticsAdminSettingsForm::tokenElementValidate()
  2. 4.x src/Form/GoogleAnalyticsAdminSettingsForm.php \Drupal\google_analytics\Form\GoogleAnalyticsAdminSettingsForm::tokenElementValidate()

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/GoogleAnalyticsAdminSettingsForm.php, line 765

Class

GoogleAnalyticsAdminSettingsForm
Configure Google_Analytics settings for this site.

Namespace

Drupal\google_analytics\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;
}