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?