How to update parent records when task is created or updated in Salesforce?

How to update parent records when task is created or updated in Salesforce?

Below sample trigger can be used to update parent records when task is created or updated.
 
Note:
I have implemented the trigger to update Opportunity alone. It do a dummy update as I have used just Id in the update DML Operation.

Sample Trigger:

trigger TaskTrigger on Task (after insert, after update) {

    Set < Id > setOpptyIds = new Set < Id >();
    
    for ( Task t : trigger.New) {
    
        if ( t.WhatId.getSobjectType().getDescribe().Name == ‘Opportunity’ ) {
        
            setOpptyIds.add(t.WhatId);
        
        }
    }
    
    if ( setOpptyIds.size() > 0 ) {
    
        List < Opportunity > listOppty = new List < Opportunity >();
        
        for ( Id opptyId : setOpptyIds ) {
        
            listOppty.add(new Opportunity(Id = opptyId));
            
        }
        
        update listOppty;
        
    }
    
}

 
Trigger to update all the object records when the Task is created or updated:
trigger TaskTrigger on Task (after insert, after update) {

    Set < Id > setRecIds = new Set < Id >();
    
    for ( Task t : trigger.New) {
    
        if ( String.isNotBlank( t.WhatId ) ) {
        
            setRecIds.add(t.WhatId);
        
        }
    }
    
    if ( setRecIds.size() > 0 ) {
    
        List < sObject > listRecs = new List < sObject >();
        
        for ( Id recId : setRecIds ) {
            
            sObject obj = recId.getSObjectType().newSObject( recId );
            listRecs.add( obj );
        
        }
        
        update listRecs;
        
    }
    
}

Leave a Reply