jQuery DataTables is a very powerful plugin for creating table with advanced interaction controls. It provides searching, sorting, pagination and many more cool features without any configuration. In this post we are going to learn how we can use this jQuery datatable in salesforce lightning components.
For download jQuery file rightclick on the page and click on save as… link OR press CTRL + S button on keyboard.
Save the JS file on your computer.
Step 2 : Upload Data Table zip file + jQuery js file as a static resources in your Salesforce org.
Static resource is a file or collection of files that is stored on Salesforce. Once your Data Table zip file and jQuery2.2.4 JS file is added as a static resource, it can be referenced by any of your lightning component.
After successfully download both files (DataTables-1.10.16.zip + jQuery js file) now, we can upload these as a static resources.
For upload zip file, from Setup >> Develop >> Static Resources >> New.
In the Name field, enter the name which is use in lightning component.
Click Choose File or Browse, and select dataTable zip file which we downloaded before.
In the Cache Control drop-down list, select Public.
Click on the Save button.
Follow same steps to upload both files.
Data Table Zip file upload…jQuery 2.2.4 JS file upload
Step 3 : Use jQuery Data Table on salesforce lightning component.
Step 4 : Create Apex Controller
From developer console >> file >> new >> Apex Class
jQueryDataTableCtrl.apxc
/*
Source : Sfdcmonkey.com
API Version: 42
Date : 3/13/2018
*/
public with sharing class jQueryDataTableCtrl {
@AuraEnabled
public static list <Opportunity> fetchOpportunity() {
Return [SELECT Name,Type,StageName,Amount,CloseDate FROM Opportunity LIMIT 500];
}
}
Step 5 : Create Lightning Component
From developer console >> file >> new >> Lightning Component
By the ltng:require tag in lightning component we can load external CSS and JavaScript libraries after we upload them as static resources.
dataTableDemoController.js
({
scriptsLoaded : function(component, event, helper) {
console.log('Script loaded..');
},
doInit : function(component,event,helper){
//call apex class method
var action = component.get('c.fetchOpportunity');
action.setCallback(this, function(response) {
//store state of response
var state = response.getState();
if (state === "SUCCESS") {
//set response value in lstOpp attribute on component.
component.set('v.lstOpp', response.getReturnValue());
// when response successfully return from server then apply jQuery dataTable after 500 milisecond
setTimeout(function(){
$('#tableId').DataTable();
// add lightning class to search filter field with some bottom margin..
$('div.dataTables_filter input').addClass('slds-input');
$('div.dataTables_filter input').css("marginBottom", "10px");
}, 500);
}
});
$A.enqueueAction(action);
},
})
I used the datatable component twice in my homepage. In one component I am able to see the search bar, pagination but in the other component it is not loading. If I remove one component , it appears in the other component. I think it gets loaded only once in a page.
I tried this in my Org but when I try to rerender the table with new data on picklist on-change event, it is showing weird results like,
1) very slow in loading
2) Still seeing old data in the table after picklist change, but I can see new data returning from the controller.
I was trying to display data based on list views. its working fine all functionality(pagination and sorting) for default list view only . when i changed list view the functionality is not working i meant pagination and sorting.
How can we reload the Datatable with new data ? i am trying to feed the Datatable with DOM source but when i destroy the Datatable and initialize it again it give me some problems: like ‘b.nTableWrapper is null’ ‘i is unidefined’ and the table data is messed up.
How can i reinitialize the table properly in salesforce Lightning Experience, because i am doing a destroy() method but it gives me errors such as: ‘b.nTableWrapper is null’ or ‘i is undefined’ . This is my table that i am updating depending on a click event:
setTimeout(function(){
jQuery(‘#tableId’).DataTable();
// add lightning class to search filter field with some bottom margin..
jQuery(‘div.dataTables_filter input’).addClass(‘slds-input’);
jQuery(‘div.dataTables_filter input’).css(“marginBottom”, “10px”);
}, 500);
I used this on a lighting component and it works perfectly in classic, however when the user is fully on lighting experience the JQuery does not seem to load. Does anyone have any idea how to fix it?
It is working fine if we test it by creating a lightning app. But if we test the datatable in Lightning epxerience, sorting is not working like Andy Aldis said.
i want to use check box for select a record and select all. and also i want to show all the records in a single page without any pagination since i have around 5000 records. if possible please help me with the sample code.
if we customize this code for multiple picklist value, which brings different values in list for selected picklist value, but while we search for specific values then its find values from outside the list of selected picklist value.
This works fine for me for component api version 39 and older. After change api version to 40 or newest than I got an exception:
aura_prod.js:907 Uncaught TypeError: Cannot read property ‘length’ of undefined
throws at https://devavanto2-accura.cs85.force.com/avanto/resource/1553006701000/datatable2/DataTables-1.10.16/media/js/jquery.dataTables.min.js:23:394 TypeError: Cannot read property ‘length’ of undefined
at Ha (jquery.dataTables.min.js:23)
at Proxy.eval (jquery.dataTables.min.js:16)
at eval (jquery225:2)
at Function.map (jquery225:2)
at n.fn.init.map (jquery225:2)
at ma (jquery.dataTables.min.js:16)
at e (jquery.dataTables.min.js:92)
at Proxy.eval (jquery.dataTables.min.js:92)
at Function.each (jquery225:2)
at n.fn.init.each (jquery225:2)
35 comments
I think “lstOpp” attribute in the component should be of type “Opportunity[]” instead of “account[]”.
opps.. my typeo mistake, Thanks for notify
Does it work with locker service enable and using lightng name space component.
Yes it will work
Does it support inline editing and record opening on clicking the record?
Hi,
I used the datatable component twice in my homepage. In one component I am able to see the search bar, pagination but in the other component it is not loading. If I remove one component , it appears in the other component. I think it gets loaded only once in a page.
Can you please tell me workaround for it?
Hi Piyush,
I tried this in my Org but when I try to rerender the table with new data on picklist on-change event, it is showing weird results like,
1) very slow in loading
2) Still seeing old data in the table after picklist change, but I can see new data returning from the controller.
Even i am facing the same issue. Did is get any solution for this
I was trying to display data based on list views. its working fine all functionality(pagination and sorting) for default list view only . when i changed list view the functionality is not working i meant pagination and sorting.
This is not responsive, could it be responsive in Ligtning Experience ?
use this :
$('#tableId').DataTable( {
responsive: true
});
How can we reload the Datatable with new data ? i am trying to feed the Datatable with DOM source but when i destroy the Datatable and initialize it again it give me some problems: like ‘b.nTableWrapper is null’ ‘i is unidefined’ and the table data is messed up.
Thanks for the help
How can i reinitialize the table properly in salesforce Lightning Experience, because i am doing a destroy() method but it gives me errors such as: ‘b.nTableWrapper is null’ or ‘i is undefined’ . This is my table that i am updating depending on a click event:
Thanks for any help
Hi, i am getting below error while loading the data table:
[$(…).DataTable is not a function]
Hi Shashank ,
did you managed to resolve the error ?
I am getting the same .
Anybody knows why it is ?
Cmake sure static resource name is correct as mentioned in the example
Hello
I have try this for jquery mobile,
but it not work. it given error.
“Uncaught TypeError: Cannot read property ‘expando’ of undefined throws a”
http://prntscr.com/jrj8gf
Hi,
Getting error message :
Uncaught ReferenceError: $ is not defined throws at https://ankitlightningdemo-dev-ed.lightning.force.com/c/components/c/dataTableDemo.js:25:21
Please let me know the issue for the same.
Than
use below code in scriptsloaded function
var $ = jQuery.noConflict();
and the below
setTimeout(function(){
jQuery(‘#tableId’).DataTable();
// add lightning class to search filter field with some bottom margin..
jQuery(‘div.dataTables_filter input’).addClass(‘slds-input’);
jQuery(‘div.dataTables_filter input’).css(“marginBottom”, “10px”);
}, 500);
Hi
While I am trying to work with the mentioned component, I am facing the following error. Can some one help me out to fix.
Uncaught ReferenceError: $ is not defined throws at https://kumarksbiz-dev-ed.lightning.force.com/c/components/c/ExampleComponent.js:25:21
many thanks in advanced.
Sravan
I used this on a lighting component and it works perfectly in classic, however when the user is fully on lighting experience the JQuery does not seem to load. Does anyone have any idea how to fix it?
It is working fine if we test it by creating a lightning app. But if we test the datatable in Lightning epxerience, sorting is not working like Andy Aldis said.
i want to use check box for select a record and select all. and also i want to show all the records in a single page without any pagination since i have around 5000 records. if possible please help me with the sample code.
how to include checkbox to select the record using jquery datatable.
check it out:
https://datatables.net/extensions/select/examples/initialisation/checkbox.html
or if you have any issue with this post your query on developer forums and share the URL here so i can help you
https://developer.salesforce.com/forums#!/feedtype=RECENT&criteria=ALLQUESTIONS&
Hello , I have used similar code but its giving me error “Cannot read property length of undefined” when records are loaded to table. please advise.
if we customize this code for multiple picklist value, which brings different values in list for selected picklist value, but while we search for specific values then its find values from outside the list of selected picklist value.
Past One Year Gone.
More Than Salesforce StackExchange.Your Blog play a big role in every developer success.
You are the real MVP.
Hi,
Can anyone help me?
1.Date fields are not sorting in this table, I need sorting for date fields also.
2. And i am using custom search in lightning component, when click on search button table data is not showing.
Thank You,
Mani
@Mani
For sorting on date fields I needed:
You’ll need to assign your dateformat to the datatable (in my case it was D-M-YYYY):
jQuery.fn.dataTable.moment( ‘D-M-YYYY’ );
And then you’ll need to assign a render like thus to the date column
render = function ( data, type, row, meta ) {if (data) {return moment(data).format(‘D-M-YYYY’);} else return null;};”)
How can we add this jquery plugin with lightning:datatable? I am unable to make it work. Thanks in advance.
This works fine for me for component api version 39 and older. After change api version to 40 or newest than I got an exception:
aura_prod.js:907 Uncaught TypeError: Cannot read property ‘length’ of undefined
throws at https://devavanto2-accura.cs85.force.com/avanto/resource/1553006701000/datatable2/DataTables-1.10.16/media/js/jquery.dataTables.min.js:23:394 TypeError: Cannot read property ‘length’ of undefined
at Ha (jquery.dataTables.min.js:23)
at Proxy.eval (jquery.dataTables.min.js:16)
at eval (jquery225:2)
at Function.map (jquery225:2)
at n.fn.init.map (jquery225:2)
at ma (jquery.dataTables.min.js:16)
at e (jquery.dataTables.min.js:92)
at Proxy.eval (jquery.dataTables.min.js:92)
at Function.each (jquery225:2)
at n.fn.init.each (jquery225:2)
Have any one the same problem?