Creating a Lightning component in your Salesforce environment requires some setup and a few applications. While it involves programming, if you understand code and can customize the sample code provided in this article, you’ll be well-equipped to get started. This guide will help you build a Lightning DataTable component using data retrieved from a Popdock API Endpoint.
The Lightning DataTable Web Component is a more complex integration than our Popdock Widget Visualforce Component, but it offers a streamlined, Salesforce-native view of your data.
Here’s what it looks like:
Before You Get Started
To build your Lightning component, you’ll need to set up a few tools and programs. Follow the steps in this Salesforce Trailhead link to get the necessary programs and extensions:
- Salesforce CLI – The Salesforce CLI allows you to interact with your Salesforce environments in various ways, such as retrieving or pushing code and interacting with data. It consists of several plugins that provide specific functionalities.
- Visual Studio Code – Visual Studio Code is the preferred code editor for Salesforce developers. It is free, open-source, and available for Windows, Linux, and macOS. It is a well-established IDE among web developers and an effective tool for building Lightning web components, thanks to free Salesforce extensions that simplify the development experience.
- Salesforce Environment – This can be your production environment, sandbox environment, or a developer environment. The provided URL includes steps for creating these environments.
Once you have these three items, you will be ready to build and publish a Lightning Component to your Salesforce Environment.
Creating a Lightning Web Component
In this section, you’ll work in Visual Studio Code to create a Salesforce Project, connect to your Salesforce environment, and begin writing the JavaScript necessary for building your Lightning component.
Create a Popdock DataTable Project
- Open Visual Studio Code.
- Press Command + Shift + P on macOS or Ctrl + Shift + P on Windows, then type “create project”. Select SFDX: Create Project, and press Enter.
- Leave the default project type selection Standard as is, and press Enter.
- Type “PopdockDataTable” as project name, and press Enter.
- Choose a directory on your local machine where the project will be stored. Click Create Project. You will now see a Welcome tab open with your POPDOCKDATATABLE project open in the Explorer.
Authorizing Your Salesforce Environment
The next steps are to authenticate your Salesforce environment. Here I am using a Dev Hub for my environment.
- In Visual Studio Code, press Command + Shift + P on macOS or Ctrl + Shift + P on Windows.
- Type “sfdx”.
- Select the Authorize option for which environment you are authorizing, here I am choosing “SFDX: Authorize an Org” since I am using a demo production environment.
- Choose the Project Default option and log in using your credentials.
- Enter an Alias or use the default. I will click Enter to accept the default.
- Click Allow.
- After you authenticate in the browser, the CLI remembers your credentials. The success message should look like this in the browser:
And then like this in the output in tab in Visual Studio Code:
To authenticate Dev Hub is a precondition for creating a scratch org, which is an ephemeral environment for developing on the Salesforce Platform. We create one in the next step. If you have authorized a Production or Sandbox environment, please skip this section.
Create a Scratch Org
- In Visual Studio Code, press Command + Shift + P on macOS or Ctrl + Shift + P on Windows.
- Type “sfdx”.
- Select SFDX: Create a Default Scratch Org….
- Press Enter to accept the default project-scratch-def.json.
- Press Enter to accept the default trailhead scratch org alias.
- Press Enter to accept the default 7 days scratch org duration.
Be patient, creating a scratch org can take a minute. The success message should look like this in the output panel of VS Code:
Create a Lightning Web Component
Creating a Lightning web component is a straightforward process. And Salesforce CLI already created a project structure that helps make getting started even easier. The folder structure looks like this:
The project we created has a special folder, “force-app/main/default”. This folder, called a package directory, contains all the metadata of your current PopdockDataTable project. Because Lightning web components are also metadata, they are stored in a subfolder named “lwc”. In the next step, we add a Lightning web component to this folder.
- Open Visual Studio Code.
- Press Command + Shift + P on macOS or Ctrl + Shift + P on Windows.
- Type “sfdx: create lightning” and select SFDX: Create Lightning Web Component.
- Then type the name that you want to give your component folder, and press Enter.
- Next choose the default directory or choose a custom directory, here I am just choosing the default.
- This creates the needed files for your first Lightning web component.
Adding Code and Metadata to Your First Lightning Web Component
Let’s take a look now at the files that make up a Lightning web component. For that you’re going to copy and paste some HTML, JavaScript, and XML that we’ve prepared for you. We start with the myFirstWebComponent.js-meta.xml file.
- Open the “PopdockDataTable” folder, which you just created in the “lwc” subfolder.
- Click PopdockDataTable.js-meta.xml.
- Replace the contents of the XML file with this XML markup:
<?xml version="1.0" encoding="UTF-8"?> <LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata"> <apiVersion>59.0</apiVersion> <isExposed>true</isExposed> <targets> <target>lightning__AppPage</target> <target>lightning__RecordPage</target> <target>lightning__HomePage</target> </targets> </LightningComponentBundle>
- Press CMD + S on macOS, or CTRL + S on Windows, to save the file.
The file that you just updated is the metadata definition file. It contains several configuration elements that control, for example, where you can add it to the Salesforce user interface using Lightning App Builder (targets). You can read more about the metadata configuration options in the documentation.
Next we create a new Javascript file and update the JavaScript file of your Lightning web component.
- In Visual Studio Code right click on “PopdockDataTable” directory and choose “New File…”. Give the new file a name, here we call it generateData.js. By entering the “.js”, Visual Studio Code knows now it is going to be a Javascript file.
- Add the following Javascript to the file, but change the {Endpoint URL} to the API Endpoint URL that you want to use and then change the {Token} to a valid Token that you have for your account or user:
export default function getCustomers() { const apiUrl = '{Endpoint URL}'; const apiKey = '{Token}'; const requestOptions = { method: 'GET', headers: { 'Authorization': 'Bearer ${apiKey}', }, }; return fetch(apiUrl, requestOptions) .then((response) => { if (!response.ok) { throw new Error('Network response was not ok'); } return response.json(); }) .catch(error => { console.error('Error:', error); }); }
- Press CMD + S on macOS, or CTRL + S on Windows, to save the file.
- Now click on PopdockDataTable.js and replace the entire contents of the file with this code:
import { LightningElement } from 'lwc'; import getCustomers from './generateData'; const columns = [ { label: 'SOP Type', fieldName: 'SOPtype', sortable: "true", hideDefaultActions: true }, { label: 'SOP No.', fieldName: 'SOPnumber', sortable: "true", hideDefaultActions: true }, { label: 'Customer ID', fieldName: 'CustomerID', sortable: "true", hideDefaultActions: true }, { label: 'Item No.', fieldName: 'Itemnumber', sortable: "true", hideDefaultActions: true }, { label: 'Description', fieldName: 'Itemdescription', sortable: "true", hideDefaultActions: true }, { label: 'Unit Cost', fieldName: 'Unitcost', type: 'currency', sortable: "true", hideDefaultActions: true }, { label: 'Unit Price', fieldName: 'Unitprice', type: 'currency', sortable: "true", hideDefaultActions: true }, { label: 'Qty', fieldName: 'Quantity', type: 'quantity', sortable: "true", hideDefaultActions: true }, { label: 'Extended Cost', fieldName: 'Extendedcost', type: 'currency', sortable: "true", hideDefaultActions: true }, { label: 'Extended Price', fieldName: 'Extendedprice', type: 'currency', sortable: "true", hideDefaultActions: true } ]; export default class PopdockTable extends LightningElement { data = []; columns = columns; sortBy; sortDirection; totalRecords; connectedCallback() { this.load(); } async load(){ this.data = await getCustomers(); this.totalRecords = this.data.length; } doSorting(e) { this.sortBy = e.detail.fieldName; this.sortDirection = e.detail.sortDirection; this.sortData(this.sortBy, this.sortDirection); } sortData(fieldname, direction) { let parseData = this.data; // Return the value stored in the field let keyValue = (a) => { return a[fieldname]; }; // checking reverse direction let isReverse = direction === 'asc' ? 1: -1; // sorting data parseData.sort((x, y) => { x = keyValue(x) ? keyValue(x) : ''; // handling null values y = keyValue(y) ? keyValue(y) : ''; // sorting values based on direction return isReverse * ((x > y) - (y > x)); }); this.data = [...parseData]; } }
- Press CMD + S on macOS, or CTRL + S on Windows, to save the file.
- Now click on PopdockDataTable.html and replace the entire contents of the file with this HTML markup:
<template> <h2 id="element-with-table-label" class="slds-text-heading_medium slds-m-bottom_xx-small">Sales Line Items from GP</h2> <h3 id="other-element-with-table-label" class="slds-text-title slds-m-bottom_small">Using an API Endpoint to create lightning datatable.</h3> <div style="height: 400px;"> <lightning-datatable key-field="SOPnumber" data={data} columns={columns} column-widths-mode="auto" sorted-by={sortBy} sorted-direction={sortDirection} onsort={doSorting} hide-checkbox-column="true"> </lightning-datatable> </div> <p style="margin: auto 0 auto 0;"><b>Total Records:</b> {totalRecords}</p> </template>
- Press CMD + S on macOS, or CTRL + S on Windows, to save the file.
Deploying Your Lightning DataTable
- Open Visual Studio Code.
- Press Command + Shift + P on macOS or Ctrl + Shift + P on Windows.
- Type “sfdx: deploy” and select SFDX: Deploy Source to Org.
- If the deployment was successful, you should see the following message on the output tab:
Adding Your Lightning DataTable to a Page in Salesforce
In this section we use the deployed Lightning Web Component and apply it to a page in Salesforce.
- Go to the page in Salesforce that you would like to the Lightning DataTable displayed. Once there, click the Setup gear icon and go to Edit Page.
- In the left menu, find the Custom section of the Components. This is where your Lightning Web Component should be showing.
- Click on the custom component you have added and drag it over to the area that you want it displayed. Once you have it, it should show a preview of what the table is going to look like. Then click the Save button.
- Now you can click the back button at the top left and return to the published page showing the Lightning DataTable that you have added.