Refresh Lightning Data Table after triggering standard event

In general way, if we will try to create a new record by NavigationMixin Create event from Lightning Data Table, it will be redirected to the detail page of newly created record, but if business wants to update the Lightning Data Table without navigating to the detail page of newly create record what will we do?

In the same way, if we will try to update the record by NavigationMixin Edit event from Lightning Data Table, the columns will not be refreshed until refreshing the entire page. In this situation how will we mitigate this problem? I think, using the following solution all the said problems will be resolved and it will help many LWC developers to make the customer happy.

Let’s discuss about this solution:

  1. Create Platform Event
  2. Create Trigger and TriggerHandler to publish the Platform Events
  3. Create Apex Class to get the records from Server
  4. Create LWC with Lightning Data Table with empAPI

Here, we will show the account records in Lightning Data Table and try to edit any account record and create a new account record from this table.

1.Create Platform Event

Create a platform event with publish behavior as publish immediately And create two custom platform fields in the event named Record Id and User Id.

2. Create Trigger and TriggerHandler to publish the Platform Events: Here, at first we will create a TriggerHandler named “AccountTriggerHandler” in this way:

In this class, we are publishing Platform Event records at the time of insert and update operations on Account records. We have added Record Id and Current User Id on each platform event records. Next, we will create a Trigger on Account object such as

3. Create Apex Class to get the records from Server: Now, we will create an Apex Class named “DataTableActionsController” for our LWC to get the Account records

Here for demo purpose, we have limited only two account records which will be returned to the next Lightning Web Component (LWC).

4. Create LWC with Lightning Data Table with empAPI: Now, finally we will create the LWC named “dataTableActions” with empAPI event:

dataTableActions.js-meta.xml

dataTableActions.js


import { LightningElement } from 'lwc';
import { NavigationMixin } from 'lightning/navigation';
import getAccounts from "@salesforce/apex/DataTableActionsController.getAccounts";
import currentUserId from '@salesforce/user/Id';
import { subscribe, unsubscribe, onError}  from 'lightning/empApi';


const actions = [
    { label: 'Edit', name: 'edit' },
];

const columns = [
    { label: 'Name', fieldName: 'Name' },
    { label: 'Account Number', fieldName: 'AccountNumber'},
    {
        type: 'action',
        typeAttributes: { rowActions: actions },
    },
];

export default class DataTableActions extends NavigationMixin( LightningElement ) {

    columns = columns;
    data = [];
    error;
    recordId;
    createdRecord = false;
    isLoading = false;
  

    subscription = {};
    CHANNEL_NAME = '/event/Refresh_Record_Event__e';

    connectedCallback() {
        this.isLoading = true;
        this.fetchAccounts();
        subscribe(this.CHANNEL_NAME, -1, this.manageEvent).then(response => {
            console.log('Subscribed Channel');
            this.subscription = response;
        });
        onError(error => {
            console.error('Server Error--->'+error);
        });
    }

    manageEvent = event=> {
        const refreshRecordEvent = event.data.payload;
        this.isLoading = true;
        console.log('Event--->'+JSON.stringify(refreshRecordEvent));
        if (!this.createdRecord && refreshRecordEvent.Record_Id__c === this.recordId && refreshRecordEvent.User_Id__c === currentUserId) {
            this.fetchAccounts();
        }
        else if (this.createdRecord && refreshRecordEvent.User_Id__c === currentUserId) {            
            this.fetchAccounts();
        }
    }
    
    fetchAccounts() {
        getAccounts()
            .then(result => {
                this.data = result;
                this.error = undefined;
            this.isLoading = false;
            })
            .catch(error => {
                this.error = error;
                this.data = undefined;
                this.isLoading = false;
            });
    }

    handleRowAction(event) {
        const actionName = event.detail.action.name;
        const row = event.detail.row;
        this.recordId = row.Id;
        switch (actionName) {
            case 'edit':
                this[NavigationMixin.Navigate]({
                    type: 'standard__recordPage',
                    attributes: {
                        recordId: row.Id,
                        objectApiName: 'Account',
                        actionName: 'edit'
                    }
                });
                break;
           
            default:
        }
    }

    createAccount(){
        this[NavigationMixin.Navigate]({
            type: 'standard__objectPage',
            attributes: {
                objectApiName: 'Account',
                actionName: 'new'
            },
            state:{
                navigationLocation: 'RELATED_LIST'
            }
        }); 
        this.createdRecord = true;
        
    }

    disconnectedCallback() {
        unsubscribe(this.subscription, response => {
            console.log('Unsubscribed Channel');
        });
    }

}

We have taken following actions in this js file.

  • We have imported Apex Class Method (“getAccounts“) to get the account records.
  • NavigationMixin is being used to take the standard create and edit operation.
  • We have imported current user id to check the current logged in user.
  • Then we have imported the empAPI with some useful methods such as subscribe, unsubscribe, onError.
  • First, we have defined the channel name as  “/event/Refresh_Record_Event__e” and subscribed the channel in connectedCallback() method.
  • Next, we have defined the messageEvent() method to notify any change on the record.
  • Lastly, we have unsubscribed the channel during the termination of the component.
  • Remaining codes, we have written for showing the records with specific columns for the Lightning Data Table.
  • Please noted that, when we have used NavigationMixin Create event in createAccount() method, we have put “state” with “navigationLocation” parameter as “RELATED_LIST” to stop the navigation to the detail page of newly created account record.

dataTableActions.html

In this html, we have defined the Lightning Data Table with row actions to show the records with specific actions such as “Edit”.So, we have solved the problem to refresh the data table without entire page refreshing when we will use standard create/ edit event from NavigationMixin library.

Thank you for giving this blog content sathiq

https://www.linkedin.com/in/sathiq-s-3aa1561a4

Leave a Comment

Your email address will not be published. Required fields are marked *