5

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?

4

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 : trigger.new){
        If(e.WhatId == null || e.What.Type != 'Account'){
            continue;
        }

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

    For (Account a : [Select Id, Name, PostalCode from Account where Id in :whatIDs.keySet()]){
        For(Event e : whatIds.get(a.id)){
            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

3
  • .Nice answer :) – Mohith Shrivastava Dec 3 '13 at 12:25
  • Thank you very much for the code. I'm just getting one error in the Developer Console which says "No such column 'PostalCode' on entity 'Account'." Any idea what the problem could be? – jmawle Dec 3 '13 at 13:18
  • Yes, not knowing your field names, I just added that. depending on how your org uses them, you likely want to use BillingPostalCode or ShippingPostalCode on the account object. – Chris Duncombe Dec 3 '13 at 13:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.