Lightning Datatable With AutoRefresh Functionality When Any Event Is Occurred In Database


Hello guys, today in this post we are going to learn how to refresh datatable when any dml event is occurred in salesforce database like insert,update,delete. In this post we will get to know how to send notification to lightning web component and how to refresh page automatically when data is change in salesforce database.

we will achieve this requirement by platform event. so first of all we will create a platform event and then fire it from trigger and we will handle it in lightning web component.

Component Features Highlights : 
  • Total Records Count
  • Refresh Datatable Automaticall
  • Refresh Apex
  • Lightning/emp api
  • Lightning Datatable
Step 1 : How to Create Platform Event In Salesforce
1.) Setup => QuickFindBox => platform => click Platform Events




2.) Create a custom Field in platform event

create a custom field as you create in custom object 
Label = > subject
Api Name => subject__c
Datatype => Text


Step 2 : Apex Trigger: accountPlatformEvent
trigger accountPlatformEvent on Account (after insert , after update,after delete ) {
 
   If(trigger.isAfter && (trigger.isUpdate || trigger.isInsert || trigger.isDelete)){
       list<AccountaccEvent = trigger.isDelete?trigger.old:trigger.new;
        List<Account_Platform_Event__epublishEvents = new List<Account_Platform_Event__e>();
        for(Account acc : accEvent){
            Account_Platform_Event__e eve = new Account_Platform_Event__e();
            eve.subject__c = acc.Name ;
            publishEvents.add(eve);            
        }
        if(publishEvents.size()>0){
            EventBus.publish(publishEvents);
        }
        
    }
}

Step 3 : Apex Controller : AccountCtrl
public class AccountCtrl {
 
    @AuraEnabled(cacheable=true)
    public static List<AccountfetchAccountRecords(){
        List<AccountlstAccount = new List<Account> ();
        for(Account acc : [SELECT Id,Name,Phone,AccountNumber,AccountSource FROM Account 
                           order by lastModifiedDate desc limit 5]){
            lstAccount.add(acc);
        }
        return lstAccount;
    }
}

Step 4 : HTML File : captureDatabaseEvent
<template>
  
<lightning-card  title="Account Datatable">
         <!-- display total record -->    
         <p class="slds-m-around_small">
            <span class="slds-badge slds-badge_lightest" style="display:inline-block">
                Total Records : {totalRecords}
            </span>
        </p>
        <!--display account dataTable s-->
    <template if:true={lstRecords}>
        <lightning-datatable
                key-field="id"
                data={lstRecords}
                columns={columns}>
        </lightning-datatable>
        </template>

        <template if:false={lstRecords}>
            <div>No Records Found</div>
            </template>
            </lightning-card>
    
</template>


Step 4 : JS File : captureDatabaseEvent
 import { LightningElementwire } from 'lwc';
 import { subscribeunsubscribeonErrorsetDebugFlagisEmpEnabled } from 'lightning/empApi';
 import  fetchAccountRecords from '@salesforce/apex/AccountCtrl.fetchAccountRecords';
 import { ShowToastEvent } from 'lightning/platformShowToastEvent';
 import { refreshApex } from '@salesforce/apex';

const columns = [
    { label: 'Name'fieldName: 'Name' },
    { label: 'Phone'fieldName: 'Phone'type: 'text' },
    { label: 'AccountNumber'fieldName: 'AccountNumber'type: 'text' },
    { label: 'AccountSource'fieldName: 'AccountSource'type: 'text' }
    
 ];
export default class CaptureDatabaseEvent extends LightningElement {
    totalRecords;
    lstRecords;
    lstStoreData;
    columns;
    /* this is your platform event name */
    channelName = '/event/Account_Platform_Event__e';
   
    /* fetch Account Records from Apex ctrl via wire */
    @wire(fetchAccountRecords)
    wiredAccounts(value) {
        this.lstStoreData =value
        if (value.data) {
        this.columns = columns;
        this.lstRecords = value.data;
        this.totalRecords =  this.lstRecords.length;
          } 
          else if (value.error) {
              console.log('fetch Data of Account error : ' + JSON.stringify(value.error));
            this.lstRecords = undefined;
        }
     
    }
    
  connectedCallback() {       
    this.handleSubscribe();   
  }


  handleSubscribe() {
    let self = this;
    /* this part will work when any event is occurred in database */
    const messageCallback = function (message) {
        var msg = message.data.payload;
        self.showToast();
        return refreshApex(self.lstStoreData);
        
    };

    // Invoke subscribe method of empApi. Pass reference to messageCallback
    subscribe(this.channelName, -1messageCallback).then(response => {
        // Response contains the subscription information on subscribe call
        console.log('Subscription request sent to: 'JSON.stringify(response.channel));
      });
 }
 /* Lightning Toast Message  */
 showToast() {
  const event = new ShowToastEvent({
      title: 'Data refreshed',
      message: 'Data has refreshed successfuly',
      variant : 'success'
  });
  this.dispatchEvent(event);
}
 }


Step 5 : XML File : captureDatabaseEvent
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>52.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
    <target>lightning__AppPage</target>
    <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>



Output :
If You have any doubt Or suggestion related this post then please comment us and share your opinion with us. We respect your opinion .

I hope you Liked it.

Happy Learning 







Post a Comment

0 Comments

Ad Code

Responsive Advertisement