How to Use Lightning Datatable in Lightning Web Component

How to Use Lightning Datatable in Lightning Web Component

Hello Trailblazers,

In this blog, we will discuss how to create lightning datatable in LWC. Lightning datatable is the way to show data in tabular form. It provides us the various features such as displaying data in a formatted way according to the datatypes, row numbering, alignment, etc.

Let's deep dive to understand it better with hands-on experience:

Scenario:

Let's suppose we have a scenario to display Opportunity data in tabular format which has a closed date in the last 30 days and the user also wants to have a search box so that it will be easier to search a particular record. Additionally, the user also wants to have a button to have the update action from the opportunity stage to closed won so that the user can select any record and update the stage to closed won.

First, we create the Apex class to prepare the data we want to display. Below is the snippet of Apex Class DisplayDataInDatatable in which we have created the method fetchOpportunity which returns the list of Opportunity having the closed date in the last 30 days and having the name specified in the searchText that will be the input from our search box.

public with sharing class DisplayDataInDatatable {

????@AuraEnabled(cacheable=true)
// fetching the list of opportunity
????public static List<Opportunity>fetchOpportunity(String searchText)

????{

????????String searchKey = '%' + searchText + '%';

????????return [Select Id,Name,StageName,Amount,CloseDate?

????????????????FROM Opportunity?

????????????????WHERE Name LIKE :searchKey?

????????????????AND CloseDate = LAST_N_DAYS:30];

????}

????@AuraEnabled
// updating the opportunity stage to Closed Won
????public static void updateOpportunityStage(List<Id> selectedOppIds)

????{

????????List<Opportunity> oppListToUpdate = new List<Opportunity>();

????????for(Opportunity opp : [Select Id,Name,StageName from Opportunity      WHERE Id IN :selectedOppIds]){

????????????opp.StageName = 'Closed Won';

????????????oppListToUpdate.add(opp);

????????}

????????if(!oppListToUpdate.isEmpty()){

????????????update oppListToUpdate;

????????}

????}

}        

Then we create our Lightning Web Component that will display data using lightning datatable with a search box and an action to update the Opportunity stage to closed won.

In our snippet, we have lightning-input of type search by which we can able to search the opportunity by its Name. onchange is the event that stores the text that we are typing in the search box.

We have <lightning-datatable> tag which displays data in tabular form. It has three major attributes:

  1. data - It is the records that will be displayed
  2. columns - It represents the columns of the table
  3. key-field - It gives each row of the table a unique identifier that helps us to display the data properly or in the correct behavior.

Additionally, here we have used onrowselection which enables us to select each row which helps us to perform any action that we want to perform? (Here we are updating the stage to Closed Won). We can hide the checkbox if we don’t want this functionality by adding hide-checkbox-column in our markup of <lightning-datatable>. If we want to show numbering in our table also we can do that by adding show-row-number-column="true"

Then we have <lightning-button> of the variant brand with the label Update. onclick we have one handler that is working to perform the update action.

//displayOppDatatable.html
<template>
<lightning-input type="search" placeholder="Search opportunity by Name..." onchange={handleChange}></lightning-input>


<lightning-datatable
    data={opportunity}
    columns={columns}
    key-field="Id"
    onrowselection={handleRowSelection}
>
</lightning-datatable>
<lightning-button variant="brand" label="Update" title="Update" onclick={handleClick}></lightning-button>
</template>        

In the below snippet, we have our JavaScript file in which we have imported @wire and @track decorator.

Next, we have also used ShowToastEvent to fire toast notifications after successfully updating our records or to show the errors.

To use the toast notification we have to import it from the lightning/platformShowToastEvent module and then we have to dispatch it by providing the message, title, and variant to it. Variant just shows whether it will be success, errors, or warning.

Example: Toast notification on success

Example :Toast Notification on Error

Now we have invoked the refreshApex to refresh our data after updating. It helps us to refresh our data without reloading the page. It returns a Promise when resolved it provides the updated data to the wire.


Next, we imported our fetchOpportunity method the from Apex class that we have created to show the list of opportunity data on the provided condition. As we can see in our class snippet we are returning the List of Opportunity having the close date in the last 30 days and also Name LIKE searchText.


Then we have to import one more method?updateOpportunityStage that we are using to update the multiple records that the user is checking from datatable to stage Closed Won.


We have declared the columns which consist of columns that we want in our datatable. Here lightning-datatable provides us the multiple features that we can set the datatype (default will be text type), alignment, inline editing, and many more.

The Label will be the column label, and fieldName is the fieldApiName of our object (here Opportunity). Ensure to include the field in your SOQL query Otherwise, it will be blank. The Type will be the datatype that we want to provide.

Here in the given screenshot, we can also set if want to wrap our data or Clip Text.

Here handleChange is the handler behind onchange event for our search box. It will fire every time we write something in the box. And this.searchText will contain the value that we put in the search window.

In the handleRowSelection handler, we are storing the records that we are selecting in the this.selectedOpp. event.detail.selectedRows contains the whole records and we are using the spread operator (...) to basically our record array in this.selectedOpp.

Now let’s talk about the handleClick that is executing after we click on the Update button

Here I have used If to check if the user has selected a record or not. If not then I am throwing one toast notification of type error.

In the other part if the user has selected the record first we are looping over the selected record then storing the Id in selectetdRows variable?then we are call our apex method then updating the record with the stage Closed Won of the Selected Opportunity records.?

We have invoked refreshApex() with the input parameter of the result that we have got in our wire method to refresh the records and get the latest data without actually reloading the window.

Note: Make sure to call refreshApex() with your whole result not just data or error then only it will work. Just like here, I have stored the whole result in the refreshedData variable.

Then we are throwing the toast notification again with variant success after updating the records.

Kindly refer below snippet.

import { LightningElement,wire,track  } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import { refreshApex } from '@salesforce/apex';
import fetchOpportunity from "@salesforce/apex/DisplayDataInDatatable.fetchOpportunity";
import updateOpportunityStage from "@salesforce/apex/DisplayDataInDatatable.updateOpportunityStage";


const columns = [
    { label: 'Opportunity name', fieldName: 'Name', type: 'text' },
    {
        label: 'Amount',
        fieldName: 'Amount',
        type: 'currency'
    },
    { label: 'Stage', fieldName: 'StageName', type: 'text' },
    { label: 'Closed Date', fieldName: 'CloseDate', type: 'date' },
];
export default class DisplayOppDatatable extends LightningElement {


@track searchText = ''
@track opportunity
columns = columns
selectedOpp = []
selectedRows = []
isLoading = true
@track refreshedData = []


// Fetching the opportunity list
@wire(fetchOpportunity,{searchText:'$searchText'})
wiredOpportunity(result){
// putting all the result to one variable for refresh 
    this.refreshedData = result 
    if(result.data){
// opportunity variable will contain the data that we are recieving
        this.opportunity = result.data
    }
    else if(result.error){
        console.log('Error fetching opportunities',error)
    }
}




// handle behing onchange for search box
handleChange(event){
this.searchText = event.target.value
}
// to handle the records that we are selecting
handleRowSelection(event){
    this.selectedOpp = [...event.detail.selectedRows]
}


handleClick(){
     if(this.selectedOpp.length == 0){
            this.dispatchEvent(
                new ShowToastEvent({
                    title: 'Error',
                    message: 'Please select atleast one opportunity',
                    variant: 'error'
                })
            );
        }
else{
  for (let i = 0; i < this.selectedOpp.length; i++) 
  {
    this.selectedRows.push(this.selectedOpp[i].Id)  
  }
     updateOpportunityStage({selectedOppIds: this.selectedRows}).then(() => {
                refreshApex(this.refreshedData)
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Success',
                        message: 'Opportunity updated successfully',
                        variant: 'success'
                    })
                );
               
            })
            .catch((error) => {
                console.log(error)
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Error',
                        message: error.statusText + '-' + error.message,
                        variant: 'error'
                    })
                );
            })
}
}


}
        

Result : Lightning datatable is working and reflecting the data with proper condition.

Result : As we can see we searched the record with Farmer and our data is getting reflected.

After selecting the record we hit the Update button then it will update that record and with the use of refreshApex() we don’t have to reload our page

Opportunity with Farmer Name got updated with Closed Won Stage.

Note: Here we have invoked the Apex method to update the Opportunity field. There are other ways by which we can perform the update action.

Conclusion

In this blog, we've explored how to create a Lightning Datatable in a Lightning Web Component (LWC) within Salesforce. The Lightning Datatable is a

powerful tool for displaying data in a tabular format, offering various features such as data formatting, row numbering, alignment, and more.

The blog walks us through a hands-on scenario where we need to display Opportunity data in a tabular format,

focusing on Opportunities with a closed date in the last 30 days. The user also requires a search box to facilitate the search for specific records and an option to update the Opportunity stage to "Closed Won."

Overall, the blog provides a comprehensive guide on creating and utilizing Lightning Datatables in Salesforce LWC, showcasing a practical example of how to implement these components to meet specific business requirements.

It demonstrates a powerful way to display and interact with data within the Salesforce ecosystem.

Also, know more about How to invoke the Apex method in LWC

Unlock the Power of Lightning Web Components: Learn How to use Lightning Datatable in your LWC!???

Learn how to use Lightning Datatable in Lightning Web Components with various row selections, search input, and update actions. Read the full article now! Also, stay tuned for more such content on Lightning Web Component(LWC).

#LightningWebComponents #Apex #Development #Salesforce #TrailblazerCommunity #Trailhead #LWC


Gaurav Bansal

Data Scientist | Large Language Models, Data Pipelines @ Coca-Cola Southwest Beverages

1 年

Thanks for sharing Kashish Bansal

Looking forward to read your blog on lightning datatable and its features in Lightning Web Component. Thank you for sharing!

要查看或添加评论,请登录

Kashish Bansal的更多文章

  • Parent Child Communication in LWC

    Parent Child Communication in LWC

    In Lightning Web Components, as a developer we sometimes need to share data across different components to break down…

  • Lightning Record Form in Lightning Web Component

    Lightning Record Form in Lightning Web Component

    Lightning-record-form is the base component that provides us with the desired functionality to create, view, and update…

  • How to use lightning/uiRecordApi In LWC

    How to use lightning/uiRecordApi In LWC

    Hello Trailblazers, In this blog, we will discuss how to use lightning/uiRecordApi in LWC. uiRecordApi is the module in…

  • How to Call Apex in Lightning Web Component

    How to Call Apex in Lightning Web Component

    Hello Trailblazers, In this blog, we will discuss about how to call Apex in Lighntning Web Component. Calling Apex in…

    2 条评论

社区洞察

其他会员也浏览了