Trigger to get fields from Object linked with the ‘Related To’ field in an Event

I have created a custom app called ‘Projects’. The app is linked with a Master-Detail field called Account which looks up an Account name and then links the Project to it. Then I create an Event which is related to the Project using the Related To field. Now, what I need to do is create 2 custom fields in the Event which will bring in the Account Name and Postcode of the Account linked in the Project. I know this is a bit tricky because of the Related To field. I’ve found this post about creating a before insert Trigger in a Task, and I wonder if this will work for an Event.

How do i specify a formula field in task to display mobile

I’ve tried adapting it to work for a Event, but can’t seem to get it to work. Is it possible to create a before insert Trigger on an Event?


Something like this should work. I did this in a text editor so there could be some syntax issues.

Trigger EventBefore on Event(before insert, before update){
    Map<Id, List<Event>> whatIds = new Map<Id, List<Event>>{};

    For (Event e :{
        If(e.WhatId == null || e.What.Type != 'Account'){

        if(whatIds.get(e.WhatId) == null){
            whatIds.put(e.whatId, new list<Event>());

    For (Account a : [Select Id, Name, PostalCode from Account where Id in :whatIDs.keySet()]){
        For(Event e : whatIds.get({
            e.yourCustomNameField = a.Name;
            e.yourCustomPostCodeField = a.BillingPostalCode;

Please note that I just modified the code from the example, but I would suggest breaking the logic out into a helper class as its not best practice to have your code inside the trigger itself.

The schema is as below so the basic logic would be to detect if the whatId is of account type and then perform logic as above

enter image description here

Source : Link , Question Author : jmawle , Answer Author : Chris Duncombe

Leave a Comment