December 27, 2019

'Callout from triggers are currently not supported' error in Salesforce

In certain scenarios, we need to make the callout from the trigger to call an external webservice however we are not able to do so as it gives the below mentioned error "Callout from triggers are currently not supported".

An Apex trigger can execute a callout when the callout is invoked within a method defined as asynchronous: that is, defined with the @future keyword. The @future annotation signifies that the Apex method executes asynchronously.

Callouts must be made asynchronously from a trigger so that the trigger process isn’t blocked while waiting for the external service's response. The asynchronous callout is made in a background process, and the response is received when the external service returns it. To make an asynchronous callout, use asynchronous Apex such as a future method.

Best practice is to call future callout method on after insert and after update events.

Sample Code:

Trigger:


  1. trigger LeadTrigger on Lead ( after insert ) {  
  2.   
  3.     Set < Id > setLeadIds = new Set < Id >();  
  4.       
  5.     for ( Lead objLead : trigger.new )   
  6.         setLeadIds.add( objLead.Id );  
  7.           
  8.     LeadTriggerHandler.updateODSLeads( setLeadIds );  
  9.   
  10. }  

Apex Class:


  1. public without sharing class LeadTriggerHandler {  
  2.   
  3.     @future (callout=true)  
  4.     public static void updateODSLeads( Set < Id > setLeadIds ) {  
  5.       
  6.         List < Lead > listLeads = [ SELECT Id, LastName FROM Lead WHERE Id IN: setLeadIds ];  
  7.         system.debug( listLeads );  
  8.       
  9.         /*Do the callout here*/  
  10.       
  11.     }  
  12.   
  13. }  

No comments:

Post a Comment