Thursday, February 4, 2021

jQuery Datatable in Lightning Web Component(lwc)

This post explains how to use jquery data tables in the lightning web component(lwc).


Prerequisites:

Step 1 : Download Required Resources 

1. Download jQuery DataTables Plugin

Click on the following link to download the DataTables library. [version 1.10.18]


This zip file includes CSS, javascript, and other files related to the plugin.

2. Download jQuery library [version 3.3.1 Recommended]

Click on the following link to download JQuery 3.3.1 minified version. [3.3.1 Recommended]


Step 2: Upload Files to static resource

upload files to static resourecs



Demo:

HTML Code:
<template>
   <lightning-card title="JQuery Datatable Demo">
      <div class="slds-m-around_medium">
         <table lwc:dom="manual"
            class="tableClass slds-table slds-table_cell-buffer slds-table_bordered" 
            style="width:100%">
         </table>
      </div>
   </lightning-card>
</template>
JS Code:
import {
    LightningElement
} from 'lwc';
import dataTableResource from '@salesforce/resourceUrl/DataTableDemo';
import JqueryResource from '@salesforce/resourceUrl/Jquery331';
import {
    loadScript,
    loadStyle
} from 'lightning/platformResourceLoader';
import {
    ShowToastEvent
} from 'lightning/platformShowToastEvent';
// import toast message event .

// import apex class and it's methods.
import getAccounts from '@salesforce/apex/LWCExampleController.getAccounts';

export default class JqueryDataTableLWCDemo extends LightningElement {
    accounts = [];
    error;

    async connectedCallback() {
        await this.fetchAccoutns();

        Promise.all([
            loadScript(this, JqueryResource),
            loadScript(this, dataTableResource + '/DataTables-1.10.18/js/jquery.dataTables.min.js'),
            loadStyle(this, dataTableResource + '/DataTables-1.10.18/css/jquery.dataTables.min.css'),
        ]).then(() => {
            console.log('script loaded sucessfully');

            const table = this.template.querySelector('.tableClass');
            const columnNames = ['Name', 'Industry', 'Type', 'Phone', 'Rating'];
            let tableHeaders = '<thead> <tr>';
            columnNames.forEach(header => {
                tableHeaders += '<th>' + header + '</th>';
            });
            tableHeaders += '</tr></thead>';
            table.innerHTML = tableHeaders;

            let jqTable = $(table).DataTable();
            $('div.dataTables_filter input').addClass('slds-input');
            $('div.dataTables_filter input').css("marginBottom", "10px");

            this.accounts.forEach(rec => {
                let tableRows = [];
                tableRows.push('<a href="/lightning/r/Account/' + rec.Id + '/view">' + rec.Name + '</a>');
                tableRows.push(rec.Industry != undefined ? rec.Industry : '');
                tableRows.push(rec.Type != undefined ? rec.Type : '');
                tableRows.push(rec.Phone != undefined ? rec.Phone : '');
                tableRows.push(rec.Rating != undefined ? rec.Rating : '');
                jqTable.row.add(tableRows);
            });
            jqTable.draw();

        }).catch(error => {
            this.error = error;
            this.dispatchEvent(
                new ShowToastEvent({
                    title: 'Error!!',
                    message: JSON.stringify(error),
                    variant: 'error',
                }),
            );
        });
    }

    async fetchAccoutns() {
        await getAccounts()
            .then(data => {
                if (data) {
                    this.accounts = data;
                }
            })
            .catch(error => {
                this.error = error;
                this.accounts = undefined;
                this.error = 'Unknown error';
                if (Array.isArray(error.body)) {
                    this.error = error.body.map(e => e.message).join(', ');
                } else if (typeof error.body.message === 'string') {
                    this.error = error.body.message;
                }
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Error!!',
                        message: error,
                        variant: 'error',
                    }),
                );
            });
    }
}
Apex Class
public inherited sharing class LWCExampleController {
	@AuraEnabled(Cacheable = true)
	public static List<Account> getAccounts(){
	  return [SELECT Id, Name,Industry, Type, Phone, Rating, AccountNumber FROM Account ORDER BY Name];
	}
}

2 comments:

  1. TypeError: Failed to execute 'insertBefore' on 'Node': parameter 1 is not of type 'Node'.
    at DocumentFragment.value [as insertBefore] (aura_prod.js:1)
    at Object.insertBefore (aura_prod.js:37)
    at Proxy.eval (jquery224:3)
    at ua (jquery224:3)
    at n.fn.init.before (jquery224:3)
    at n.fn.init.n.fn. [as insertBefore] (jquery224:3)
    at mb (jquery.dataTables.min.js:31)
    at ga (jquery.dataTables.min.js:48)
    at e (jquery.dataTables.min.js:92)
    at Proxy.eval (jquery.dataTables.min.js:92)

    I am getting this error when i am trying to inialize the datatable

    ReplyDelete
  2. Bro give me your number

    ReplyDelete