Apex Trigger Whenever a Contact is updated (Email / Phone), Salesforce calls external REST API again using Queueable Apex | Salesforce sends Contact data using POST REST API using Queueable Apex

107 views

Apex Trigger Whenever a Contact is updated (Email / Phone), Salesforce calls external REST API again using Queueable Apex | Salesforce sends Contact data using POST REST API using Queueable Apex

REAL-TIME BUSINESS SCENARIO (POST + QUEUEABLE)

๐Ÿ“Œ Scenario

๐Ÿ‘‰ Download Free Ebook โ†’

๐Ÿ‘‰ Get Complementary โ†’

right side banner -- www.w3webmart.com
  • Salesforce has Contacts not yet synced with an External CRM
  • Salesforce sends Contact data using POST REST API
  • External system returns:
    • externalCustomerId
  • Salesforce:
    • updates the Contact with External ID
    • creates a new Log record (example: Integration Log)
  • Whenever a Contact is updated (Email / Phone):
    • Salesforce calls external REST API again using Queueable Apex

 

Salesforce Setup

Custom Fields of Contact

  • External_Customer_Id__c (Text)

 

Custom Object (optional but real-world)

  • Integration_Log__c:
    • Request__c (Long Text)
    • Response__c (Long Text)
    • Status__c (Text)

Step 1 Account Trigger (After Update): ContactPracticeTrigger.apxt

  1.   TRIGGER ContactPracticeTrigger ON Contact (BEFORE INSERT, after INSERT, BEFORE UPDATE, after UPDATE) {
  2.  
  3.     IF(TRIGGER.isAfter){
  4.  
  5.         IF(TRIGGER.isUpdate){
  6.  
  7.             List<Id> conIds = NEW List<Id>();
  8.  
  9.             FOR(Contact con:TRIGGER.new){
  10.  
  11.                 Contact oldData =  TRIGGER.oldMap.get(con.Id);
  12.  
  13.                 IF(con.Phone != oldData.Phone || con.Email != oldData.Email){
  14.                     conIds.add(con.Id);
  15.                 }
  16.  
  17.             }
  18.  
  19.             IF(!conIds.isEmpty()){
  20.                 ContactPracticeQueueable que = NEW ContactPracticeQueueable(conIds);
  21.                 System.enqueueJob(que);
  22.                 //System.enqueueJob(NEW ContactPracticeQueueable(conIds));
  23.             }
  24.  
  25.         }
  26.  
  27.     }
  28.  
  29. }

 

 

Step 2 Apex Controller: ContactPracticeQueueable.apxc


๐ŸŽ Up to 99% Off Courses (Coupon)
๐Ÿ’ฅ Use Promo Code: STANDARDOFFER๐Ÿ’ฅ
๐Ÿš€ Get Free Salesforce Course Access: www.thevijaykumar.w3web.net

  1.  
  2. public class ContactPracticeQueueable implements Queueable, DATABASE.AllowsCallouts{
  3.  
  4.     public List<Id> contactIds;
  5.  
  6.     public ContactPracticeQueueable(List<Id> ids){
  7.          this.contactIds = ids;
  8.     }
  9.  
  10.     public void EXECUTE(QueueableContext qc) {
  11.  
  12.         List<Contact> conObjList = [SELECT Id, FirstName, LastName, Email, Phone, External_Customer_Id__c FROM Contact WHERE Id IN:contactIds];
  13.  
  14.         List<Contact> conItem = NEW List<Contact>();
  15.         List<Integration_Log__c> logs = NEW List<Integration_Log__c>();
  16.  
  17.  
  18.         FOR(Contact con:conObjList){
  19.  
  20.           Http h = NEW Http();
  21.           HttpRequest req = NEW HttpRequest();
  22.           req.setEndpoint('https://reqres.in/api/users'); // Public test API
  23.           req.setMethod('POST');
  24.           req.setHeader('Content-Type', 'application/json');
  25.           req.setHeader('x-api-key', 'reqres_4d079b1969e2489f803812be427d6bc3');        
  26.           //req.setBody('{"fname":con.FirstName, "lname":con.LastName, "email":con.Email, "phone":con.Phone}');
  27.  
  28.           Map<String, Object> bodyData = NEW Map<String, Object>();
  29.           bodyData.put('fname',con.FirstName);
  30.           bodyData.put('lname',con.LastName);
  31.           bodyData.put('email',con.Email);
  32.           bodyData.put('phone',con.Phone);
  33.           req.setBody(JSON.serialize(bodyData));
  34.  
  35.          HttpResponse res = h.send(req);
  36.          system.debug('StatusCode ' + res.getStatusCode());
  37.  
  38.             Integration_Log__c log = NEW Integration_Log__c();
  39.             log.Request__c = req.getBody();
  40.             log.Response__c = res.getBody();
  41.             log.Status__c  = String.valueOf(res.getStatusCode());
  42.  
  43.             logs.add(log);
  44.  
  45.             system.debug('logs##### ' + logs);
  46.  
  47.         IF(res.getStatusCode() == 200 || res.getStatusCode() == 201){
  48.  
  49.             Map<String, Object> resData = (Map<String, Object>) json.deserializeUntyped(res.getBody());
  50.             system.debug('resData ' + resData);
  51.  
  52.             string resId = (String) resData.get('id');
  53.  
  54.             con.External_Customer_Id__c = resId;
  55.             conItem.add(con);
  56.           }
  57.  
  58.         }
  59.  
  60.         IF(!conItem.isEmpty()){
  61.             UPDATE conItem;
  62.         }
  63.  
  64.         IF (!logs.isEmpty()) {
  65.             INSERT logs;
  66.         }
  67.  
  68.     }
  69.  
  70.  
  71. }

 

Further post that would you like to learn in Salesforce

 

FAQ (Frequently Asked Questions)

Can we use trigger new in after update?

trigger. new is available only on insert, update, and undelete triggers and represents the new version of the records after the trigger event.

How do you call an external API from Salesforce using Apex?

To call an API from Apex, use a named credential, which specifies the URL of a callout endpoint and its required authentication parameters. By security policy, sessions created by Lightning components aren't enabled for API access. This restriction prevents even your Apex code from making API calls to Salesforce.

What are the limitations of Queueable apex?

Limitations of Queueable Apex: Job Depth Limit: Queueable Apex allows a maximum of 5 chained jobs in a single transaction. Exceeding this limit results in a runtime error. Future Methods do not have this limitation, as they cannot be chained.

Related Topics | You May Also Like

๐Ÿ‘‰ Get Complementary โ†’

right side banner -- www.w3webmart.com
 
  
๐Ÿ‘‰ Get Free Course โ†’

๐Ÿ“Œ Salesforce Administrators

๐Ÿ“Œ Salesforce Lightning Flow Builder

๐Ÿ“Œ Salesforce Record Trigger Flow Builder

๐Ÿ‘‰ Get Free Course โ†’

๐Ÿ“Œ Aura Lightning Framework

๐Ÿ“Œ Lightning Web Component (LWC)

๐Ÿ“Œ Rest APIs Integration



Hi, This is Vijay Kumar behind the admin and founder of w3web.net. I am a senior software developer and working in MNC company from more than 8 years. I am great fan of technology, configuration, customization & development. Apart of this, I love to write about Blogging in spare time, Working on Mobile & Web application development, Salesforce lightning, Salesforce LWC and Salesforce Integration development in full time. [Read full bio] | | The Sitemap where you can find all published post on w3web.net