datatable

Powerful Lightning Datatable base component – Example Using Fieldset

Lightning Component

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.

  1. Get the data from Server.
  2. Use <table> html element with aura:iteration in component markup.
  3. 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"
        "/>

RequiredAtt datatable

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.

field-set datatable

 

field-set new

add fieldset datatable

  • 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:

lightning datatable-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: 

25 comments

Leave a Reply