jQuery dataTable in LWC Image

How To Use jQuery Data Table In Salesforce Lightning Web Component

DataTables is a very powerful open source jQuery plugin for displaying data in HTML tables and adding interactions to them. This jquery plugin provides following inbuilt features without any additional configuration : 

  • Pagination [Previous, next and page navigation.]
  • Instant search [Filter results by text search.]
  • Multi-column ordering [Sort data by multiple columns at once.]
  • Easily theme-able
  • Mobile friendly [Tables adapt to the viewport size.]
  • Fully internationalisable [Easily translate DataTables into multiple languages]
  • Free open source software
  • And many more cool features..

In this tutorial you will learn about how to use jquery DataTables plugin in salesforce lightning web component. 

   In order to use the DataTables plugin, you have to include the jQuery and  DataTables libraries in your lightning web component via static resources. 

Prerequisites

Before proceeding with this tutorial, you should have a basic understanding of lwc,javascript and apex.

New to LWC? Quick Start: Lightning Web Components

Step 1 : Download Required Resources 

Download jQuery DataTables Plugin

Download jQuery library [version 2.2.4 Recommended]

  • jQuery library is not included with the DataTables zip file – you have to download it separately.
  • Click on the following link to download JQuery 2.2.4 minified version. [2.2.4 Recommended]
  • https://code.jquery.com/jquery-2.2.4.min.js
  • To download the jQuery file, right click on the page and click on ‘save as’ or use [CTRL + S] button from your keyboard to save the JS file on your computer.

Step 2 : Upload Files As Salesforce Static Resource

      Static resource is a file or collection of files that is stored on salesforce. Once we upload DataTables zip file and jQuery2.2.4 js files in static resource, it can be referenced by any of your lightning web components.

  • After successfully downloading both files (DataTables-1.10.16.zip + jQuery js file), you can upload these as static resources in salesforce.
  • To upload zip file, from SetupStatic ResourcesNew.
  • In the Name field, enter the name which will be used in the lightning web component js.
  • Click Choose File or Browse, and select dataTable zip from your computer
  • In the Cache Control drop-down list, select Public.
  • Click on the Save button.
Repeat the same steps to upload both files.

Step 3 : Create Apex Class To Fetch Opportunity Records

  1. In Visual Studio Code, open the Command Palette by pressing Ctrl+Shift+P (Windows) or Cmd+Shift+P (macOS).
  2. Type sfdx and Select SFDX: Create Apex Class.
  3. Enter JQueryDataTableCtrl for class name and Press Enter.
  4. Copy and paste the following code and save the file.

Apex Class  :

/*
  Source : lwcFactory.com
  API : 50
*/
public with sharing class JQueryDataTableCtrl {
   // Apex method to fetch Opportunites records
    @AuraEnabled 
    public static list <Opportunity> fetchOpportunity() {
       return [SELECT Name,Type,StageName,Amount,CloseDate
               FROM Opportunity LIMIT 500];
     }
}

Step 4 : Create Lightning Web Component

 In VS Code, open the Command Palette by pressing Ctrl+Shift+P (Windows) or Cmd+Shift+P (macOS).

  1. Type sfdx and Select SFDX: Create Lightning Web Component.
  2. Enter jQueryDataTablesDemo for the name of the new web component and Press Enter.

Copy and paste the following code in the HTML file and save.

<template>

    <lightning-card  title="Opportunity Data With jQuery DataTable">
            <div class="slds-m-around_medium">
                <table lwc:dom="manual"
                       class="tableCls slds-table slds-table_cell-buffer slds-table_bordered" 
                       style="width:100%">
                </table>
            </div>        
    </lightning-card>
    
</template>

When using these 3rd party libraries in a Lightning web component, add lwc:dom=”manual” to any HTML element that you want to manipulate with JavaScript. When the engine sees the directive, it preserves encapsulation.

Js code :

 // Source : lwcFactory.com
import { LightningElement } from 'lwc';
import { loadStyle, loadScript } from 'lightning/platformResourceLoader';
// import jquery & dataTables library from static resource
import jQuery224 from '@salesforce/resourceUrl/jQuery224';
import dataTable from '@salesforce/resourceUrl/dataTable';
// import apex class method from salesforce module 
import fetchOpportunity from '@salesforce/apex/JQueryDataTableCtrl.fetchOpportunity';

export default class JQueryDataTablesDemo extends LightningElement {

    recordsQueried = [];  // array property to store list of Opportunity 
   
    // The connectedCallback() lifecycle hook fires when a component is inserted into the DOM.
    async connectedCallback() {
       // call apex class method which will return the list<Opportunity>
       // assign returned list of records to ‘recordsQueried’ property       
        this.recordsQueried = await fetchOpportunity();

      // load jQuery, and DataTables [JS and CSS] from static resource 
        Promise.all([
            loadScript(this, jQuery224 ),
            loadScript(this, dataTable + '/DataTables-1.10.16/media/js/jquery.dataTables.min.js'),
            loadStyle(this, dataTable + '/DataTables-1.10.16/media/css/jquery.dataTables.min.css')
        ])
        .then(() => { 
            // get the table tag reference from html template using class   
            const table = this.template.querySelector('.tableCls');
            // set table headers 
            const columnHeaders = ['Name' ,'StageName','Amount', 'CloseDate' , 'Type'];
            
            // create html table header part 
            let columnHeaderHtml = '<thead> <tr>';
            columnHeaders.forEach(function(header) {
                columnHeaderHtml += '<th>' + header + '</th>';
            });
            columnHeaderHtml += '</tr></thead>';

           // set <thead> element inside table element 
            table.innerHTML = columnHeaderHtml;
            
           //  apply dataTable library to the table and store reference in a variable 
            let oDataTable =  $(table).DataTable();
           
           // process all Opportunity records in a for loop and generate table row        
            this.recordsQueried.forEach(function(opp) {
                let tableRow = []; 
                let sUrl = '/lightning/r/Opportunity/' + opp.Id + '/view'; 
                 tableRow.push('<a href="' + sUrl + '">' + opp.Name + '</a>');
                 // if any field value is undefined then set blank string to avoid errors
                 tableRow.push(opp.StageName != undefined ? opp.StageName : '');
                 tableRow.push(opp.Amount != undefined ? opp.Amount : '');  
                 tableRow.push(opp.CloseDate != undefined ? opp.CloseDate : '');  
                 tableRow.push(opp.Type != undefined ? opp.Type : '');  
                 oDataTable.row.add(tableRow);
            }) 
           // use DataTables plugin draw function to reflect your data changes on UI
            oDataTable.draw();
        });
    }
}

Meta XML file code :

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

    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
        <target>lightningCommunity__Default</target>
        <target>lightningCommunity__Page</target>
        <target>lightning__Tab</target>
        <target>lightning__Inbox</target>
    </targets>
</LightningComponentBundle>

Check code comments to get explanation of code

Thanks for reading and stay tuned! If you found this tutorial helpful then don’t forget to share 🙂

Related Posts

3 thoughts on “How To Use jQuery Data Table In Salesforce Lightning Web Component

Leave a Reply

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