Score:0

How can I fire a Google analytics tag event on every form post?

bi flag

I want to see statistics for forms submissions, grouped by type of forms. I am using Google Analytics 4 (https://www.drupal.org/docs/contributed-modules/google-analytics/using-google-analytics-4x). I tried adding a GA event on form submit like this:

 /**
 * Implements hook_form_alter().
 */
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  // Add the tracking functionality to the form
  $form['#submit'][] = 'mymodule_form_submission_tracking_handler';
}

function mymodule_form_submission_tracking_handler($form, &$form_state) {
  // some logic to check the form category 
  ...
  $event_data = [
    'event_category' => $category,
    'event_action' => 'Submit',
  ];
  $event_data_json = json_encode($event_data);
  $element = [
    '#type' => 'html_tag',
    '#tag' => 'script',
    '#attributes' => [
      'type' => 'text/javascript',
    ],
    '#value' => "gtag('event', 'FormSubmit', $event_data_json);",
  ];
  $renderer = \Drupal::service('renderer');
  $renderer->render($element);
}

But I can't see my event in the GA dashboard when checking real time reports. I also cleared the caches after adding the code. Maybe I should try adding some custom dimensions and metrics like this https://developers.google.com/analytics/devguides/collection/gtagjs/custom-dims-mets but I don't know where I should place my code. Any ideas?

id flag
Does the script execute? What does the browser console say? Did you try console logging the data? Is gtag a global function?
user5274714 avatar
bi flag
I added a console.log into the #value and I suppose the script is not executed, as nothing is logged. I've seen gtag is used in the GA script that was added in the <head> tag of the page, I assume it is global.
id flag
Your code does not attach anything to the form so I don't suppose it would ever work as written.
user5274714 avatar
bi flag
So what should I attach to the form? Should I move the gtag function into a js file and attach it to the form?
Jaypan avatar
de flag
Simply rendering the code won't do anything, as Google Analytics acts on JS, so it it needs to be inserted into the page.
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.