How to transfer tasks back to Lead after conversion in Salesforce?

How to transfer tasks back to Lead after conversion in Salesforce?

Make sure the users have “View and Edit Converted Leads” permission.

Check this https://www.infallibletechie.com/2018/10/profile-permission-to-view-and-edit.html for more information on this permission.

Sample Code:


Trigger:


  1. trigger LeadTrigger on Lead ( after update ) {  
  2.   
  3.     Map < Id, Id > mapOpptyIdLeadId = new Map < Id, Id >();  
  4.       
  5.     for ( Lead objLead : trigger.new  ) {  
  6.         /* 
  7.             Once the Lead is converted, getting the Converted Opportunity Id 
  8.         */  
  9.         if ( String.isNotBlank( objLead.ConvertedOpportunityId ) && String.isBlank( trigger.oldMap.get( objLead.Id ).ConvertedOpportunityId ) )          
  10.             mapOpptyIdLeadId.put( objLead.ConvertedOpportunityId, objLead.Id );  
  11.           
  12.     }  
  13.       
  14.     if ( mapOpptyIdLeadId.size() > 0 ) {  
  15.       
  16.         /* 
  17.             Calling the Queueable interface to transfer the tasks 
  18.         */  
  19.         System.enqueueJob( new TransferActivities( mapOpptyIdLeadId ) );  
  20.           
  21.     }  
  22.   
  23. }  



Queueable Interface:


  1. public class TransferActivities implements Queueable {  
  2.   
  3.     Map < Id, Id > mapOpptyIdLeadId = new Map < Id, Id >();  
  4.       
  5.     public TransferActivities( Map < Id, Id > mapOpptyIdLeadId ) {  
  6.       
  7.         this.mapOpptyIdLeadId = mapOpptyIdLeadId;  
  8.           
  9.     }  
  10.   
  11.     public void execute( QueueableContext qc ) {  
  12.                   
  13.         List < Task > listTasks = [ SELECT Id, WhatId, WhoId FROM Task WHERE WhatId IN: mapOpptyIdLeadId.keySet() ];  
  14.           
  15.         for ( Task objTask : listTasks ) {  
  16.           
  17.             system.debug( ‘Lead Id is ‘ + mapOpptyIdLeadId.get( objTask.WhatId ) );  
  18.             objTask.WhoId = mapOpptyIdLeadId.get( objTask.WhatId );  
  19.             /* 
  20.                 Setting WhatId to null since Task cannot be linked to Lead and Opportunity 
  21.             */  
  22.             objTask.WhatId = null;  
  23.           
  24.         }  
  25.           
  26.         update listTasks;  
  27.           
  28.     }  
  29.   
  30. }  

Leave a Reply