Another way of doing it (especially if you use the GTM Configuration Tag to deploy your GA4 over your site, as gtag requires you to use the gtag.js deployed) is through GTM dataLayer:
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
'event': 'aSpecificEventName',
'form_type_DL': 'contact_us'
});
And then configure in GTM a new variable 'form_type_DL'
, configure a new trigger based on a custom event, defining the event name as (in my case) 'aSpecificEventName'
and finally, set in GTM a new GA4 Event tag, with your new trigger recently created sending the event name and event parameters as you like, for example one of the parameters can be form_type and its value would be {{form_type_DL}}
, the one sent through our dataLayer push that will contain 'contact_us'
.
So the right order of the steps would be:
- Define your new variables in GTM with a specific variable name(only if you need to send a specific value to GA4)
- Create and configure your custom event-driven trigger with a specific event name
- Create a new GA4 Event-driven tag adding your previously-created trigger and adding your parameter value(of any event parameter you decide to use if ever needed) as the variable previously created.
- Finally, set in your code the dataLayer push, making sure the event value is the same as the trigger event name and the variables matches your variables.
Going further on this explanation to have a better understanding of what we do, if we take a closer look at the gtag.js code we are suggested to manually install:
<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-XYZXYZXYZ"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-XYZXYZXYZ');
</script>
The gtag() function we are supposed to do to push a GA4 event does a dataLayer.push(), so it's a way of simplifying/automating the process I first explained.
https://developers.google.com/analytics/devguides/collection/ga4/events?client_type=gtag
https://support.google.com/tagmanager/answer/7582054?hl=en