You are here

function google_analytics_form_user_form_alter in Google Analytics 8.2

Same name and namespace in other branches
  1. 8.3 google_analytics.module \google_analytics_form_user_form_alter()
  2. 4.x google_analytics.module \google_analytics_form_user_form_alter()

Implements hook_form_FORM_ID_alter().

File

./google_analytics.module, line 392
Drupal Module: Google Analytics.

Code

function google_analytics_form_user_form_alter(&$form, FormStateInterface $form_state) {
  $config = \Drupal::config('google_analytics.settings');
  $account = $form_state
    ->getFormObject()
    ->getEntity();
  if ($account
    ->hasPermission('opt-in or out of google analytics tracking') && ($visibility_user_account_mode = $config
    ->get('visibility.user_account_mode')) != 0 && _google_analytics_visibility_roles($account)) {
    $account_data_google_analytics = \Drupal::service('user.data')
      ->get('google_analytics', $account
      ->id());
    $form['google_analytics'] = [
      '#type' => 'details',
      '#title' => t('Google Analytics settings'),
      '#weight' => 3,
      '#open' => TRUE,
    ];
    switch ($visibility_user_account_mode) {
      case 1:
        $description = t('Users are tracked by default, but you are able to opt out.');
        break;
      case 2:
        $description = t('Users are <em>not</em> tracked by default, but you are able to opt in.');
        break;
    }
    $form['google_analytics']['user_account_users'] = [
      '#type' => 'checkbox',
      '#title' => t('Enable user tracking'),
      '#description' => $description,
      '#default_value' => isset($account_data_google_analytics['user_account_users']) ? $account_data_google_analytics['user_account_users'] : $visibility_user_account_mode == 1,
    ];

    // hook_user_update() is missing in D8, add custom submit handler.
    $form['actions']['submit']['#submit'][] = 'google_analytics_user_profile_form_submit';
  }
}