I have a requirement. Contact related to Task, I need to pull his functional role
(custom field) on Task page layout. So whenever I create or edit a Task and relate with any contact so his/her functional role
(Custom field) Value should populate automatic on Task Page field(Functional role
).
Please help! How can I achieve it? I tried formula field but unable to get. I tried through trigger but it is not working. Please check my code and let me know what I am doing wrong.
Please find below code:
// This trigger fires on newly inserted or reparented Tasks associated with conortunities,
// and stores the conty's current functional role value in the contact functional role field
trigger updatefunctionalrole1 on Task(before insert, before update) {
// Create a map between the contact ID and its functional role value
Map < ID, String > confunrole1 = new Map < ID, String > ();
List < Task > conTasks = new List < Task > ();
// Loop through the triggered Tasks and add all of the contact IDs (for those associated with conortunities)
for (Task t: trigger.new) {
// Only Tasks associated with conortunities
if (t.whoID != null && (String.valueOf(t.whoID)).startsWith('003')) {
// And only newly inserted Tasks or those being reparented to an contact
if (trigger.isInsert || (trigger.isUpdate && t.WhoID != trigger.oldMap.get(t.id).WhoID)) {
confunrole1.put(t.whoID, '');
conTasks.add(t);
}
}
}
// Query the conortunities and add their functional role to the map
for (contact con: [SELECT Functional_Role__c FROM contact WHERE ID IN: confunrole1.keySet()]) {
confunrole1.put(con.id, con.Functional_Role__c);
}
// Update the contact functional role field on the Task with the relevant value
for (Task t: trigger.new) {
t.functional_role__c = confunrole1.get(t.whoID);
}
}
Kindly suggest what to do?
conTasks
. And then there is the updating of tasks t.functional_role__c that were excluded from the query of the contacts (on update if contact did not change the field would be nulled)