+ Start a Discussion
Russell baker 1Russell baker 1 

Trigger to Pull related contact's details on Task page when new task creates.

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:
 
trigger updatefunctionalrole on Task (before insert, before update) {

Map<ID,String> confunrole = new Map<ID,String>();
List<Task> conTasks = new List<Task>();


for (Task e : trigger.new) {

    if (e.whoID!= null && (String.valueOf(e.whoID)).startsWith('003'))  {

        if (trigger.isInsert || (trigger.isUpdate && e.WhoID != trigger.oldMap.get(e.id).WhoID)) {
            confunrole.put(e.whoID,'');
            conTasks.add(e);
        }
    }
}

for (contact con : [SELECT Functional_Role__c FROM contact WHERE ID IN :confunrole.keySet()]) {
    confunrole.put(con.id,con.Functional_Role__c);
}
// Update the contact functional role field on the Task with the relevant value
for (Task e : trigger.new) {
    e.functional_role__c = confunrole.get(e.whoID);
}
}

 
George AdamsGeorge Adams
What is not working about this trigger? Are you getting any errors in debug?

Your code works perfectly for me.

Maybe drop some system.debug() statements into the control loops to see what the trigger is actually doing.