Home SALESFORCEAPEX How to get the Contact Id while creating the Task using Apex Trigger

How to get the Contact Id while creating the Task using Apex Trigger

by Sakthivel Madesh

How to get the Contact Id while creating the Task using Apex Trigger

while creating the task to contact, its possible to get the contact information from Task WhoId or WhatId field and below is the example code:

[java]
Set<id> contactIds = new Set<id>();

if (Trigger.isInsert) {
for (Task item : Trigger.new) {
if(item.WhoId != null && (((String)item.WhoId).substring(0,3) == ‘003’) ) {
contactIds.add(item.WhoId);
}
}
}
[/java]

Same way we can get the Opportuntiy/Account/any other custom object with starting 3characters of object/record id.

[java]
Set<id> opportunityIds = new Set<id>();
if (Trigger.isInsert) {
for (Task item : Trigger.new) {
if(item.WhatId != null && (((String)item.WhatId).substring(0,3) == ‘006’) ) {
opportunityIds.add(item.WhoId);
}
}
}

[/java]

Difference between WhatId and WhoId in Events and Task

You may also like

Leave a Comment