0
votes

I am trying to write a trigger to update the 'Name' field (so WhoId in the API) to the 'Name' (ContactId) of the custom Primary Contact field of the Account the Task is related to.

trigger updateNameToPrimary on Task (after insert, after update) {
    for(Task t : Trigger.new) {
        t.WhoID = [SELECT Account.Id 
                   FROM Account 
                   WHERE Id = :t.Id].Custom_Primary_Contact__c;        
    }
}

I have been doing some testing and don't think it's working and cannot figure out why. Just looking for a point in the right direction as I still am in the learning process.

1

1 Answers

0
votes

Change Trigger from "after insert after update" To "before insert before update". Something like this

trigger updateNameToPrimary on Task (before insert, before update) {
    set<Id> accIdSet = new  set<Id>();
    for(Task t : Trigger.new) {
       if(t.AccountId!=null)
        accIdSet.add(t.AccountId);        
    }
   map<Id,Account> accMap = new map<Id,Account>([select Custom_Primary_Contact__c from Account where Id in:accIdSet]); 
   for(Task t : Trigger.new) {
        if(t.AccountId!=null && accMap.containsKey(t.AccountId))
        t.WhoID = accMap.get(t.AccountId).Custom_Primary_Contact__c;      
    }
}