SFDC Stop - Always the latest about Salesforce


Full Tutorial Series with videos, free apps, live sessions, salesforce consulting and much more.


Telegram logo   Join our Telegram Channel

Monday, 11 April 2022

Lightning Datatable in LWC | How to create a lightning-datatable in LWC?

Hello Trailblazers,


In this post we're going to learn how we can create a lightning datatable in lwc. In order to create a lightning datatable we use the lightning-datatable tag where we need to specify 3 attributes:


key-field: To specify a unique identifier for each row of the table. It'll be a string specifying the key column in the data that we need to use to identify each row.

data: Information to be displayed in the datatable. The value passed to this attribute should be a javascript array.

columns: Information about columns of the datatable. This include column name and other metadata associated with it like: type, fieldName, icon details etc. The value passed to this attribute should be a javascript array as well.


Now let's see how we can create a very simple datatable to display employees information. Each employee will have some attributes including: Employee Id, First Name, Last Name, Phone Number and Email Address. We're going to consider these 5 attributes for now and will create a datatable showcasing the data with these columns. Let's create a lightning web component now!!


We're going to name our component: employeeDatatable. First things first, we're going to display this component at the homepage, so let's setup that:

employeeDatatable.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>54.0</apiVersion>
    <isExposed>true</isExposed>
    <masterLabel>Employee Datatable</masterLabel>
    <description>This datatable is used to display employee records.</description>
    <targets>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>

As you can see in the above code snippet, I have specified a target as lighting__Homepage as we want to include this datatable in homepage and the isExposed tag has a value as true because we want to search that component in the lightning app builder. The masterLabel and description attributes are optional but nice to have. You can search the component by it's masterLabel if it's provided, otherwise, you'll search it by it's actual name. Let's move onto html now.

employeeDatatable.html

<template>
    <div style="height: 250px;">
        <lightning-datatable
            key-field="employeeId"
            data={employeeData}
            columns={employeeColumns}>
        </lightning-datatable>
    </div>
</template>
Above you can see the full html code for our datatable. You don't need anything else to display the data. No tr, td, thead or any more tags. As you can see above, key-field attribute has a value as employeeId because our employeeId will be unique and we can use it to uniquely identify each row. Next our data attribute has a value as employeeData and the columns attribute has the value as employeeColumns. Remember, employeeData will be a javascript array and employeeColumns will also be a javascript array.

Note: You may have seen code specifying data={data} and columns={columns}. Don't get confused by this. In data={data} the data before the "=" sign is the attribute name and the {data} after the "=" sign is the attribute value which is nothing but an array defined in our js file which will store the data. Similarly, in columns={columns}, the columns before the "=" sign is the attribute name and the {columns} after the "=" sign is the attribute value which is again an array defined in our js file which will store the columns information. This is the reason I am using different names for my variables above.

Now, let's see the js part!

employeeDatatable.js

import { LightningElement } from 'lwc';

export default class EmployeeDatatable extends LightningElement {

    employeeColumns = [
        { label: 'Employee Id', fieldName: 'employeeId' },
        { label: 'First Name', fieldName: 'firstName' },
        { label: 'Last Name', fieldName: 'lastName' },
        { label: 'Phone Number', fieldName: 'employeePhone', type: 'phone' },
        { label: 'Email Address', fieldName: 'employeEemail', type: 'email' }
    ];

}

As you can see above, I've defined a javascript array named employeeColumns which we have referred in our html. This is an array of objects where each object is going to have a label and a fieldName. The value of the label will be displayed as the column heading and the value of the fieldName is used to identify what information should be displayed under this column, we'll see this in detail as we define employeeData. For now, let's focus on the columns.

By default, each column will have a datatype as text. You can also specify a type attribute to specify the datatype of a particular column. Lightning Datatable will automatically apply the formatting according to the type of the column defined. Isn't it great?

Note: The fieldName can be anything and doesn't depend on the label or type of the data.

In our employeeColumns array above, we've kept the first 3 columns as text and the next two columns have a datatype of phone and email respectively. You can now go to your salesforce homepage. Click on Setup -> Edit Page and you can search for the Employee Datatable component in the lightning appbuilder as shown below: 


This is coming because we've exposed our lwc component: <isExposed>true</isExposed> tag in the .js-meta.xml file. You just need to drag and drop this component into the homepage and save it (activate as org default if necessary).

Once you've embedded this component in the homepage. It'll look as shown below:


As you can see above, we've defined the columns of our datatable here. The labels are the column names and we don't have any data because we haven't defined the employeeData variable yet in our js file. We have defined a height for this datatable as we've specified <div style="height: 250px;"> in our html code. div is the parent of our lightning-datatable here and is used to restrict the datatable expansion to a specified height.

Now, let's add the data to our datatable as well. For this, we'll define another js array named employeeData as shown below:
    employeeData = [
        {
            employeeId: '1',
            firstName: 'Richard',
            lastName: 'Hendricks',
            employeePhone: '(158) 389-2794',
            employeeEmail: 'richard@piedpiper.com'
        },
        {
            employeeId: '2',
            firstName: 'Jared',
            lastName: 'Dunn',
            employeePhone: '(518) 390-2749',
            employeeEmail: 'jared@piedpiper.com'
        },
        {
            employeeId: '3',
            firstName: 'Erlich',
            lastName: 'Bachman',
            employeePhone: '(815) 391-2974',
            employeeEmail: 'erlich.bachman@piedpiper.com'
        }
    ];
As you can see above, I have added 3 employee records to my employeeData array. Notice that In each record, the key is exactly the "fieldName" that we mentioned in employeeColumns array before, namely: employeeId, firstName, lastName, employeePhone and employeeEmail. This is most important to understand how the data is mapped to columns. Sharing the below image which should clarify the mappings in a better way:


The output of the above code is given below:


As you can see we have 3 entries in our datatable based on the 3 objects (records) in our employeeData array. Notice that the phone number and email address values are formatted automatically as we have mentioned the correct type for those. I am sharing the full js code below for your convinience:
import { LightningElement } from 'lwc';

export default class EmployeeDatatable extends LightningElement {

    employeeColumns = [
        { label: 'Employee Id', fieldName: 'employeeId' },
        { label: 'First Name', fieldName: 'firstName' },
        { label: 'Last Name', fieldName: 'lastName' },
        { label: 'Phone Number', fieldName: 'employeePhone', type: 'phone' },
        { label: 'Email Address', fieldName: 'employeeEmail', type: 'email' }
    ];

    employeeData = [
        {
            employeeId: '1',
            firstName: 'Richard',
            lastName: 'Hendricks',
            employeePhone: '(158) 389-2794',
            employeeEmail: 'richard@piedpiper.com'
        },
        {
            employeeId: '2',
            firstName: 'Jared',
            lastName: 'Dunn',
            employeePhone: '(518) 390-2749',
            employeeEmail: 'jared@piedpiper.com'
        },
        {
            employeeId: '3',
            firstName: 'Erlich',
            lastName: 'Bachman',
            employeePhone: '(815) 391-2974',
            employeeEmail: 'erlich.bachman@piedpiper.com'
        }
    ];
}
Once, we add a lot of data to our datatable by filling up employeeData array, it'll look as shown below:


In this tutorial, we learned about the basics of lightning datatable and how we can implement our own lightning datatable in lwc. I hope you liked the post, let me know your feedback in the comments down below.

Happy Trailblazing!!

No comments:

Post a Comment