Skip to main content

Capture Real time data using CDC(Change Data Capture) in Salesforce | SF Fact #05


Change Data Capture (CDC) enables receiving near-real-time updates for Salesforce records and synchronizing them with an external data store. CDC publishes change events that reflect modifications to Salesforce records, including new records, updates, deletions, and undeletions. These events can be subscribed to in a Lightning Web Component (LWC) using the Emp API.

To meet the business requirement of creating a task whenever a user manually changes an opportunity's status to "Closed Won," use CDC events and a generic LWC on the opportunity record page. This solution avoids the need for Apex triggers or record-triggered flows.


How to enable CDC?
  • Go to setup
  • Search Change Data Capture
  • Add Entities



The lightning/empApi module provides access to methods for subscribing to a streaming channel and listening to event messages. All streaming channels are supported, including channels for platform events, PushTopic events, generic events, and Change Data Capture events. This component requires API version 44.0 or later.

Note: Below code is for example purpose, you can modify it according to your requirements.

changeDataCaptureSubscriber.js


import { LightningElement, api } from 'lwc';
import { subscribe, unsubscribe, onError } from 'lightning/empApi';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
export default class EmiApiCallout extends LightningElement {
    channelName = '/data/CaseChangeEvent';
    subscription = {};
    @api recordId;

    subscribed;

    // Tracks changes to channelName text field
    handleChannelName(event) {
        this.channelName = event.target.value;
    }

    renderedCallback() {
        if (!this.subscribed) {
            this.handleSubscribe();
            this.subscribed = true;
        }
    }

    // Initializes the component
    connectedCallback() {
        // Register error listener
        this.registerErrorListener();

    }

    // Handles subscribe button click
    handleSubscribe() {
        // Callback invoked whenever a new event message is received
        const messageCallback = (response) => {
            console.log('New message received: 'JSON.stringify(response));
            // Response contains the payload of the new message received
            this.handleMessage(response);
        };

        // Invoke subscribe method of empApi. Pass reference to messageCallback
        subscribe(this.channelName, -1, messageCallback).then(response => {
            // Response contains the subscription information on subscribe call
            console.log('Subscription request sent to: 'JSON.stringify(response.channel));
            this.subscription = response;
        });
    }

    // Handles unsubscribe button click
    handleUnsubscribe() {
        // Invoke unsubscribe method of empApi
        unsubscribe(this.subscription, (response) => {
            console.log('unsubscribe() response: 'JSON.stringify(response));
            // Response is true for successful unsubscribe
        });
    }

    registerErrorListener() {
        // Invoke onError empApi method
        onError((error) => {
            console.log('Received error from server: 'JSON.stringify(error));
            // Error contains the server-side error
        });
    }

    handleMessage(response) {
        if (response) {
            if (response.hasOwnProperty('data')) {
                Console.log('data check here '+ response);
            }
        }
    }
}

changeDataCaptureSubscriber.js-meta.xml


<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>56.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__RecordPage</target>
    </targets>
</LightningComponentBundle>


DEMO:






THANKS AND HAPPY CODING!!!





 

Comments

Popular Posts

Top 100 Most common used Apex Method in Salesforce

  Here are 100 more Apex methods in Salesforce: 1.       insert: Inserts records into the database. 2.       update: Updates records in the database. 3.       delete: Deletes records from the database. 4.       upsert: Updates or inserts records into the database. 5.       query: Retrieves records from the database using SOQL. 6.       getContent: Retrieves the content of a document or attachment. 7.       getContentAsPDF: Generates a PDF file from a Visualforce page or HTML content. 8.       addError: Adds a custom error message to a record and prevents saving. 9.       start: Initiates processing in batch Apex. 10.    execute: Processes a batch of records in batch Apex. 11.    finish: Finalizes processing in batch Apex....

How to create ICS/Calendar File | Helps you to download the calendar invites

  Want to know how to create ICS(Internet Calendar Scheduling) file for Business purpose....👀    ICS (Internet Calendar Scheduling) file is a calendar file saved in a universal calendar format used by several email and calendar programs, including Microsoft Outlook, Google Calendar, Notes and Apple Calendar. It enables users to publish and share calendar information on the web and over email. Lets see the code. The code is written in lwc(Lightning web component). HTML:   <template> <div class="login-container"> <h1 style="size: 14px;"><b>Create ICS File</b></h1> <div class="form-group"> <lightning-input type="datetime" name="input1" value={EventEndValue} onchange={startDate} label="Enter Start date/time value" ></lightning-input> </div> <div class="form-group"> <lightning-input type="...

Sharing records by Apex in Salesforce

  Greetings, everyone! In today's session, we'll delve into the topic of sharing records within an Apex class. As we're aware, there exist various methods through which we can accomplish the sharing of records. We engage in record sharing primarily when the object's Organization Wide Default (OWD) settings are set to private. Sharing settings come into play when certain predefined criteria are met, allowing us to extend access to records to designated groups or roles. In cases where intricate logic is involved, manual sharing is employed. While this approach proves beneficial for specific records, instances where a multitude of records require automated handling, Apex sharing becomes the preferred solution. Salesforce offers a 'Share' object for each type of object, with distinct naming conventions: For standard objects, it's 'StandardobjectName+Share', such as 'AccountShare' for the 'Account' object. Custom objects follow the pattern...

Login Salesforce Without Credentials(Without UserName and Password)

  Want to login into Salesforce without credentials. Please follow the below STEPS: STEPS:-  1)  Goto to setup  --> Open Developer Console. 2) Goto debug --> Open Execute Anonymous Window --> It will open the pop. 3) Please write the below code in Anonymous window.       String sessionId = UserInfo.getOrganizationId() + '' + UserInfo.getSessionId().SubString(15);      System.debug('$$$$ Session Id ' + sessionId); 4) Click on Execute and filter the debug. You can see one session Id with Organization Id. Now, we have to copy the debug session Id and create one login URL. Steps to create Login URL: 1) Copy the Salesforce URL. Please refer the screenshot shown below. 2) Now concatenate the session Id with the salesforce URL and your Session Id Will look like below. https://d5g000004zfq2eai-dev-ed.lightning.force.com/secur/frontdoor.jsp?sid=00D5g000004zfQ2EAI!AQgAQKzTcnQTifXpRnQ7DgECtk_rv.w9BT5FoPEAmoy_UrgG4HJ6B9YFpQ2LVlmnJhBrYPSf8cI...

SF Fact #03 | Undelete Failed, Entity is not in recycle bin

  Similar to ENTITY_IS_DELETED error, if we attempt to undelete a record from recycle bin by mistake which has already been hard deleted, the following error is encountered: UNDELETE_FAILED. When a record is deleted, it moves to the Recycle Bin. This is known as "soft deletion," allowing the record to be easily restored through the user interface. However, under certain conditions, a deleted record will no longer appear in the Recycle Bin: Master-Detail Relationship (Child Deleted First): If a record is a child or detail in a master-detail relationship and it is deleted before its parent record, then after the parent is deleted, the child record transitions to a "hard deleted" status. In this state, the child record cannot be recovered through the Recycle Bin and must be recreated if needed. Master-Detail Relationship (Parent Deleted): If a record is a child or detail in a master-detail relationship and the parent record is deleted, the child record is also soft del...