SalesforceBlue

Feel the rhythm of Salesforce

Aura

Lightning Data Table Simplified

Lightning Data Table lets you display tabular data where each column can be displayed based on the data type. For example, an email address is displayed as a hyperlink with the mailto: URL scheme by specifying the email type. The default type is text.

Use lightning:datatable component to create data table.

Let’s explore it with few examples.

Please create an Aura Component with the name MyDataTableComponent.

Implementing Basic Data Table Using lightning:datatable

Please save the following code into MyDataTableComponent.

<aura:component>
<aura:attribute name="data" type="Object" />
<aura:attribute name="columns" type="List" />

<aura:handler name='init' value='{!this}' action='{!c.doInit}' />

<lightning:datatable
    keyField="id"
    data="{! v.data }"
    columns="{! v.columns }"
    hideCheckboxColumn="true"/>

</aura:component>	

Let’s understand the attributes used in lightning:datatable:

keyField: Associates each row with a unique ID.

data: The array of data to be displayed.

columns: Array of the columns object that’s used to define the data types

hideCheckBoxColumn: Hides or displays the checkbox column for row selection. To hide the checkbox column, set hideCheckboxColumn to true. The default is false.

({
    doInit : function(component, event, helper) {
        component.set("v.columns", [
            {label:"First Name", fieldName: "FirstName" , type:"text"},
            {label:"Last Name", fieldName: "LastName" , type:"text"},
            {label:"Email", fieldName: "Email" , type:"email"}
        ]);

        component.set("v.data", [
            {"FirstName":"Tony", "LastName":"Stark", "Email":"TonyStark@gmail.com"},
            {"FirstName":"Bruce", "LastName":"Banner", "Email":"BruceBanner@gmail.com"},
            {"FirstName":"Steve", "LastName":"Rogers", "Email":"SteveRogers@gmail.com"}
        ]);
    }
})

In the above JavaScript block, we are doing two things.

First is setting up the columns with the respected values by giving the label for the column, fieldName of the column and type(data type) of the column.

Secondly, we are setting up the actual data in the data attribute. Here we have given the data manually for this basic example. In the project, you may be required to fetch the data from the Apex Controller to load it up in your data table.

Below is the preview of this example:

Implementing Sorting Rows In lightning:datatable:

Please save the following code into MyDataTableComponent.

<aura:component>
<aura:attribute name="data" type="Object" />
<aura:attribute name="columns" type="List" />
<aura:attribute name="sortDirection" type="String" default="asc" />
<aura:attribute name="defaultSortDirection" type="String" default="asc" />
<aura:attribute name="sortedBy" type="String" />

<aura:handler name='init' value='{!this}' action='{!c.doInit}' />

<lightning:datatable
    keyField="id"
    data="{! v.data }"
    columns="{! v.columns }"
    hideCheckboxColumn="true"
    defaultSortDirection="{!v.defaultSortDirection}"
    sortedDirection="{!v.sortDirection}"
    sortedBy="{!v.sortedBy}"
    onsort="{!c.handleSort}"/>

</aura:component>	
({
    doInit : function(component, event, helper) {
        component.set("v.columns", [
            {label:"First Name", fieldName: "FirstName" , type:"text", sortable:true},
            {label:"Last Name", fieldName: "LastName" , type:"text", sortable:true},
            {label:"Email", fieldName: "Email" , type:"email", sortable:true}
        ]);

        component.set("v.data", [
            {"id":1, "FirstName":"Tony", "LastName":"Stark", "Email":"TonyStark@gmail.com"},
            {"id":2, "FirstName":"Bruce", "LastName":"Banner", "Email":"BruceBanner@gmail.com"},
            {"id":3, "FirstName":"Steve", "LastName":"Rogers", "Email":"SteveRogers@gmail.com"}
        ]);
    },
    handleSort: function (cmp, event, helper) {
        var fieldName = event.getParam('fieldName');
        var sortDirection = event.getParam('sortDirection');
        // assign the latest attribute with the sorted column fieldName and sorted direction
        cmp.set("v.sortedBy", fieldName);
        cmp.set("v.sortedDirection", sortDirection);
        helper.sortData(cmp, fieldName, sortDirection);
    }
})
({
    sortData: function (cmp, fieldName, sortDirection) {
        var data = cmp.get("v.data");
        var reverse = sortDirection !== 'asc';
        //sorts the rows based on the column header that's clicked
        data.sort(this.sortBy(fieldName, reverse))
        cmp.set("v.data", data);
    },
    sortBy: function (field, reverse, primer) {
        var key = primer ?
            function(x) {return primer(x[field])} :
            function(x) {return x[field]};
        //checks if the two rows should switch places
        reverse = !reverse ? 1 : -1;
        return function (a, b) {
            return a = key(a), b = key(b), reverse * ((a > b) - (b > a));
        }
    }
})

To enable sorting of row data by a column label, set sortable to true for the column on which you want to enable sorting.

Set sortedBy to match the fieldName property on the column. Clicking a column header sorts rows by ascending order unless the defaultSortDirection is changed, and clicking it subsequently reverses the order.

Handle the onsort event handler to update the table with the new column index and sort direction.

Below is the preview of this component:

Implementing Actions In lightning:datatable

Please save the following code into MyDataTableComponent.

<aura:component>
<aura:attribute name="data" type="Object" />
<aura:attribute name="columns" type="List" />

<aura:handler name='init' value='{!this}' action='{!c.doInit}' />

<lightning:datatable
    keyField="id"
    data="{! v.data }"
    columns="{! v.columns }"
    hideCheckboxColumn="true"
    onrowaction="{! c.handleRowAction }"/>

</aura:component>	
({
    doInit : function(component, event, helper) {
        var actions = [
            {label: "Show Details", name: "show_details"},
            {label: "Delete", name: "delete"}
        ];

        component.set("v.columns", [
            {label:"First Name", fieldName: "FirstName" , type:"text"},
            {label:"Last Name", fieldName: "LastName" , type:"text"},
            {label:"Email", fieldName: "Email" , type:"email"},
            {type: "action", typeAttributes: {rowActions: actions}}
        ]);

        component.set("v.data", [
            {"id":1, "FirstName":"Tony", "LastName":"Stark", "Email":"TonyStark@gmail.com"},
            {"id":2, "FirstName":"Bruce", "LastName":"Banner", "Email":"BruceBanner@gmail.com"},
            {"id":3, "FirstName":"Steve", "LastName":"Rogers", "Email":"SteveRogers@gmail.com"}
        ]);
    },
    handleRowAction : function (component, event, helper) {
        var action = event.getParam("action"); 
        var row = event.getParam("row");

        switch (action.name) {
            case "show_details":
                console.log('Details: ' + JSON.stringify(row));
                break;

            case "delete":
                helper.removeData(component, row);
                break;
        
            default:
                break;
        }
    },
})
({
    removeData: function (component, row) {
        var rows = component.get('v.data');
        var rowIndex = rows.indexOf(row);

        rows.splice(rowIndex, 1);
        component.set('v.data', rows);
    }
})

Row-level actions refer to tasks you can perform on a row of data, such as updating or deleting the row.

Static actions apply to all rows on the table. You can perform actions on each row and handle them using the onrowaction event handler.

Below is the preview of this component:

Implementing Inline Editing In lightning:datatable

Please save the following code into MyDataTableComponent.

<aura:component>
<aura:attribute name="data" type="Object" />
<aura:attribute name="columns" type="List" />
<aura:attribute name="saveDraftValues" type="Object"/>

<aura:handler name='init' value='{!this}' action='{!c.doInit}' />

<lightning:datatable
    keyField="id"
    data="{! v.data }"
    columns="{! v.columns }"
    hideCheckboxColumn="true"
    onsave="{! c.handleSave }"/>

</aura:component>	
({
    doInit : function(component, event, helper) {
        var actions = [
            {label: "Show Details", name: "show_details"},
            {label: "Delete", name: "delete"}
        ];

        component.set("v.columns", [
            {label:"First Name", fieldName: "FirstName" , type:"text", editable:true},
            {label:"Last Name", fieldName: "LastName" , type:"text", editable:true},
            {label:"Email", fieldName: "Email" , type:"email", editable:true}
        ]);

        component.set("v.data", [
            {"id":1, "FirstName":"Tony", "LastName":"Stark", "Email":"TonyStark@gmail.com"},
            {"id":2, "FirstName":"Bruce", "LastName":"Banner", "Email":"BruceBanner@gmail.com"},
            {"id":3, "FirstName":"Steve", "LastName":"Rogers", "Email":"SteveRogers@gmail.com"}
        ]);
    },
    handleSave : function (component, event, helper) {
        var draftValues = event.getParam("draftValues"); 

        console.log('draftValues >> ' + JSON.stringify(draftValues));
    },
})

Make a column editable by setting editable to true when you are defining your columns in the controller.

You can handle the oncancel, oncellchange, and onsave actions when the cell value changes or is saved.

The draftValues data structure is an array of objects. Each object describes the changed values by specifying the keyField to identify the row containing the changed values, the data column name, and the changed value for that column.

Here in this example, we have not made any server calls. However, on the project, you may be required to make a server call to save and commit the draftValues in your Salesforce org.

Below is the preview of this component:


Thank you for visiting SalesforceBlue.com
If you have any queries feel free to write down a comment below 🙂


Leave a Reply

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