
Powerful Lightning Datatable base component – Example Using Fieldset
SFDC Monkey wishes you a happy and prosperous new year. We hope you all had a great long weekend. Let’s continue the same momentum throughout this year and achieve your goals.
It’s been a quite some time since lightning has launched. We have seen a lot of new features and improvements to make Lightning Experience super awesome. With the same momentum, Salesforce had released a bunch of base components in Winter 18 release and we would like to discuss one of the powerful base components in this post.
If you are working in lightning projects, You must have created a table to display the data.
You might have done below steps to achieve the requirement.
- Get the data from Server.
- Use <table> html element with aura:iteration in component markup.
- Apply SLDS styling to look better.
This process might look easy and fine if you are familiar with lightning. But what if we want to make this table reusable ? Of course, this can also be done but it is not that straight forward like you are thinking. You may end up with performance issue as well.
With winter 18 release, Salesforce has released an awesome component called lightning:datatable. This is a base component and it simplified the above process with few lines of markup. We just have to get the data and columns to be displayed in the table and set the required attributes in the component.
Inline editing is currently not supported
Supported features include:
- Displaying and formatting of columns with appropriate data types
- Resizing of columns
- Selecting of rows
- Sorting of columns by ascending and descending order
Syntax:
<lightning:datatable data="{! v.mydata }" columns="{! v.mycolumns }" keyField="id" "/>
These are the some of the attributes we would be using in this example. In short, we just have to set the columns and data attributes to display the column headers and data accordingly. hideCheckboxColumn attribute hides the check boxes on every row, by default check boxes are visible. KeyField attribute is required to identify the each row with a unique id and for better performance.
We have a lot of attributes in lightning:datatable to perform sorting, resizing columns, giving custom width and row selection with checkboxes. This post is focused on basic agenda of lightning:datatable. We will cover all other functionalities in later posts.
The following example fetches the data from Account object and display the data using lightning:datatable base component. I used a fieldset to refer the columns to be displayed. (You can use your own way). This way we do not have to hard code any of the columns and it will become dynamic .
Example:
Step 1: FieldSet Creation
To create a field set, switch to salesforce classic >> Go to Account Object >> Select FieldSets.
Click on [New] >> drag and drop the fields to be displayed on the table.
- click on Save button.
Step : 2 Server Side Controller – Apex Class (LightningDataTableController .apxc)
public class LightningDataTableController { /* Method Name : getAccRecords Purpose : To get the wrapper of Columns and Headers */ @AuraEnabled public static DataTableResponse getAccRecords(String strObjectName, String strFieldSetName){ //Get the fields from FieldSet Schema.SObjectType SObjectTypeObj = Schema.getGlobalDescribe().get(strObjectName); Schema.DescribeSObjectResult DescribeSObjectResultObj = SObjectTypeObj.getDescribe(); Schema.FieldSet fieldSetObj = DescribeSObjectResultObj.FieldSets.getMap().get(strFieldSetName); //To hold the table hearders List<DataTableColumns> lstDataColumns = new List<DataTableColumns>(); //Field to be queried - fetched from fieldset List<String> lstFieldsToQuery = new List<String>(); //The final wrapper response to return to component DataTableResponse response = new DataTableResponse(); for( Schema.FieldSetMember eachFieldSetMember : fieldSetObj.getFields() ){ String dataType = String.valueOf(eachFieldSetMember.getType()).toLowerCase(); //This way we can set the type of a column //We do not get the exact type from schema object which matches to lightning:datatable component structure if(dataType == 'datetime'){ dataType = 'date'; } //Create a wrapper instance and store label, fieldname and type. DataTableColumns datacolumns = new DataTableColumns( String.valueOf(eachFieldSetMember.getLabel()) , String.valueOf(eachFieldSetMember.getFieldPath()), String.valueOf(eachFieldSetMember.getType()).toLowerCase() ); lstDataColumns.add(datacolumns); lstFieldsToQuery.add(String.valueOf(eachFieldSetMember.getFieldPath())); } //Form an SOQL to fetch the data - Set the wrapper instance and return as response if(! lstDataColumns.isEmpty()){ response.lstDataTableColumns = lstDataColumns; String query = 'SELECT Id, ' + String.join(lstFieldsToQuery, ',') + ' FROM Account'; System.debug(query); response.lstDataTableData = Database.query(query); } return response; } //Wrapper class to hold Columns with headers public class DataTableColumns { @AuraEnabled public String label {get;set;} @AuraEnabled public String fieldName {get;set;} @AuraEnabled public String type {get;set;} //Create and set three variables label, fieldname and type as required by the lightning:datatable public DataTableColumns(String label, String fieldName, String type){ this.label = label; this.fieldName = fieldName; this.type = type; } } //Wrapper calss to hold response - This response is used in the lightning:datatable component public class DataTableResponse { @AuraEnabled public List<DataTableColumns> lstDataTableColumns {get;set;} @AuraEnabled public List<sObject> lstDataTableData {get;set;} public DataTableResponse(){ lstDataTableColumns = new List<DataTableColumns>(); lstDataTableData = new List<sObject>(); } } }
Step 3: Create a Lightning Component
LightningDataTable.cmp
<aura:component implements="flexipage:availableForAllPageTypes" controller="LightningDataTableController"> <aura:attribute name="mydata" type="Object"/> <aura:attribute name="mycolumns" type="List"/> <aura:handler name="init" value="{!this}" action="{!c.doInit}" /> <lightning:datatable data="{! v.mydata }" columns="{! v.mycolumns }" keyField="Id"/> </aura:component>
LightningDataTableController.js
({ doInit : function(component, event, helper) { helper.getDataHelper(component, event); }, })
LightningDataTableHelper.js
({ getDataHelper : function(component, event) { var action = component.get("c.getAccRecords"); //Set the Object parameters and Field Set name action.setParams({ strObjectName : 'Account', strFieldSetName : 'DataTableFieldSet' }); action.setCallback(this, function(response){ var state = response.getState(); if(state === 'SUCCESS'){ component.set("v.mycolumns", response.getReturnValue().lstDataTableColumns); component.set("v.mydata", response.getReturnValue().lstDataTableData); }else if (state === 'ERROR'){ var errors = response.getError(); if (errors) { if (errors[0] && errors[0].message) { console.log("Error message: " + errors[0].message); } } else { console.log("Unknown error"); } }else{ console.log('Something went wrong, Please check with your admin'); } }); $A.enqueueAction(action); } })
LightningApp – To test this component
<aura:application extends="force:slds"> <c:LightningDataTable /> </aura:application>
check also : Custom Data Table With Inline Editing In Salesforce Lightning Component – Sample
Output:
If you want to remove or add the columns to this table, You do not have to touch the code. Just go to the field set, add/remove fields accordingly. Awesome right ?
Please share your feedback and comment if any questions. Happy Learning.
Follow us on Facebook and twitter further updates.
Resources:
Lightning Developer Guide: lightning:dataTable
About The contributor:
Brahmaji Tammana
Name: Brahmaji Tammana
Email: [email protected]
Salesforce Associate
Post By Brahmaji :
- Spring 18 Lightning Components Features/Enhancement/Critical Updates – Highlights
- How To Detect a Device In Salesforce Lightning Component ?
- Powerful Lightning Datatable base component – Example Using Fieldset
- How to use design resource in Lightning Component ?
- Use Lightning Data Service – No To Apex Controller In Lightning Components
- Override Standard Buttons With Lightning Component – Lightning Experience
- Custom Record Type Selection Lightning Component with force:createRecord event
- How to Add Lightning Component as a Quick Action in Salesforce
- How to use SVG in Salesforce Lightning Component ?
- Work Fast With Keyboard Shortcuts in Salesforce Lightning Experience
25 comments
Hi.. I am doing the same thing but my columns are not expanding the text. The text is getting wrapped. I am to manually stretch it to open fully.
I checked the https://www.lightningdesignsystem.com/components/data-tables/
but I did not get which class will make it fully expanded.
Use minColumnWidth attribute in tag.
Eg.
Hi this Naidu from Hyderabad I’m recently moved into salesforce development side. I got a new lightning project.
I need a support for this project from lightning developer if anyone interested call me +91 8686716461
Hello,
I m using Lightning Tree Grid component , and when I see the datatable all the properties are same.
I wanted to change the help text of the column header, the attribute title is not working .
Can you please check it
Can i make the column headers of this data table as bold? And can i make the lightning data table headers as fixed while the data can be scrollable? Can you suggest a way of doing it
How to make Name column a link instead of plain text ? Any idea to make Lookup columns using Lightning Data Table ?
Hello ,
Do we have any idea how can I make name field as link . It showing as text
Hi,
thank you for sharing the wonderful post.
I am trying to use same for custom object, and have defined same in helper but getting error:
strObjectName is not defined
Kindly, help me.
thanks in advance.
Hi,
Thank you.
I found a solution.
Thank you for helpful post.
How to handle the related object fields
Hello, nice guide. Any ideas how we can dynamically change classes for data calls or add icons? E.g. for Active column make green/red background and/or add approve/close icon based on Yes/No value in the cell?
HI I need test class for this ,,,its very urgent can u pls provide test class for this………….
Hi Using Lightning data table i am displaying records .I use field sets to display columns but filed set displays Ids and references as ids so i handled this in js helper and displaying them as links but my requirement is to show mini pagelayout whenever i hover over that links .Can someone help
Brilliant post Bhramaji keep it up!
This is awesome. Thanks!
how to enable inline editing in the above piece of code
how to enable inline editing in the above code?
how to make dataTable tag support mobile devices
How to give hyperlink for the account name to redirect to corresponding account
This is pretty great! But, columns based on a relationship are not working. Do you have any advice on that?
Jeff, Ever find a solution?
Can you please give test class as well of this
LightningDataTableController .apxc