function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Saranya MSaranya M 

Trigger on event/task referring contact object. When creating event/task for other objects, throws error

I have written a trigger on event for contact object. If I try to create an event for Merchandise object, the below trigger is getting fired and throws an error.

How I can restrict the below trigger to work only for events created on contact object.

trigger ContactSysIDEvent on Event (before insert) {
    ID evid;
   for (event e:trigger.new)
    { evid=e.whoid;
    contact m123 =[select name,id_type__C,sys_id__c,siebel_id__C from contact
                          where id=:evid];
    if(m123.id_type__C=='Sys ID')
        { e.Contact_sys_ID__c=m123.sys_id__c; }
        else{ e.contact_sys_id__C=m123.siebel_id__C; }
}
}
Arpit Patel 8Arpit Patel 8
Hi Saranya,

what you can do is,

1. Get the "keyPrefix" of Contact object from the GetDescribe call...
2. Use a for loop in the trigger to parse Trigger.New and check if the ParentId of the event that is created starts with the KeyPrefix. If it starts with the KeyPrefix of Contact then use that it means that the particular record is of Contact.
3. Add it to a new List and do all the process on new list rather than Trigger.New.

This way trigger will fire for events on all object, however the new list will have event records pertaining to Contact only.

Hope this help.

Saranya MSaranya M
I have modified the query to use the kepyprefix. What else should I do? 

trigger ContactSysIDEvent on Event (before insert) {
Schema.DescribeSObjectResult r = Contact.sObjectType.getDescribe();
String keyPrefix = r.getKeyPrefix();
    String evid;
       for (event e:trigger.new)
    { evid=e.whoid;
     if(evid.startswith(keyprefix)){
    contact m123 =[select name,id_type__C,sys_id__c,siebel_id__C from contact
                          where id=:evid];
    if(m123.id_type__C=='Sys ID')
        { e.Contact_sys_ID__c=m123.sys_id__c; }
        else{ e.contact_sys_id__C=m123.siebel_id__C; }

}
}
}