Introduction:
Are you looking to build a versatile data table in your Salesforce application? Look no further! In this blog, we will explore how to create a powerful, generic data table Lightning Web Component (LWC) in Salesforce. This LWC component will be highly customizable and offer features such as sorting, clickable URLs, and pagination. Let’s dive in!
Component Properties
To build a flexible and reusable data table LWC, we will first define a set of component properties. These properties will allow users to configure the component according to their specific needs. Here’s a list of the properties we will include in our generic data table LWC:
a. Fields Api Names: This property accepts a comma-separated list of field API names to display in the table. Example: “Name,CreatedDate,CustomField__c”
b. Fields Labels: This property accepts a comma-separated list of field column labels to display in the table. Example: “Name,Created Date,Custom Field”
c. sObjectName: This property allows users to specify the API name of the sObject. The name is used to fetch the data. Example: “Account”
d. Url Field: This property accepts a field API name. It will be displayed as a value in the table column. It will redirect to the sObject record when clicked. Example: “Name”
e. Allow Sorting: This property is a boolean value that determines whether sorting should be enabled for the data table.
f. Sorting Columns: This property accepts a comma-separated list of field API names that should be sortable in the table. Example: “Name,CreatedDate,CustomField__c”
g. Page Size Options: This property accepts a comma-separated list of string values for page size options. Example: “5,10,25”
h. Page Size Default Value: This property sets the default page size for the table. Example: “10”
Implementing Features
Now that we have defined our component properties, let’s explore the features we will implement in our generic data table LWC:
- Clickable URL to redirect to a record: This feature allows users to click on a specified field. They will be redirected to the sObject record. This provides quick and easy access to the record details.
- Customizable sorting columns: When the Allow sorting on table columns property is checked, users can choose specific sortable columns. This feature gives them more control over their data analysis.
- Custom page size options: This feature allows users to select the number of rows displayed per page. It provides a more streamlined view of the data.
- Default page size selection: Users can set a default page size for the table. This ensures a consistent user experience across different tables.
- Pagination with dynamic page numbers: This feature provides pagination controls that adapt based on the number of pages. If there are less than 10 pages, the component will display all the page numbers. If there are more than 10 pages, it will show ellipses between page numbers. This format indicates additional pages.
Building the Component
In this section, we will discuss how to build our generic data table LWC component. We will cover its HTML structure. We will also look at its JavaScript implementation and CSS styling.
a. HTML Structure
To create the HTML structure for our data table component, we will use the lightning-datatable base component provided by Salesforce. This component is designed specifically for displaying tabular data and comes with built-in support for sorting and pagination.
Here’s our component’s HTML file:
genericDataTable.html
b. JavaScript Implementation
In the JavaScript file, we will define the component’s properties, fetch the data from the specified sObject, handle sorting, and create the columns based on the provided fields and labels.
Here’s our component’s JavaScript file:
genericDataTable.js
c. Metadata File
genericDataTable.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="myLWCComponent">
<apiVersion>62.0</apiVersion>
<isExposed>true</isExposed>
<masterLabel>Generic Data Table</masterLabel>
<description>A generic data table LWC component.</description>
<targets>
<target>lightning__AppPage</target>
<target>lightning__RecordPage</target>
<target>lightning__HomePage</target>
<target>lightningCommunity__Page</target>
<target>lightningCommunity__Default</target>
<target>lightning__Tab</target>
</targets>
<targetConfigs>
<targetConfig targets="lightning__AppPage,lightning__RecordPage,lightning__HomePage">
<property name="fields" label="Fields Api Names" type="String"
default="Name,Phone,CreatedDate"
description="Enter a comma-separated list of field api names to display in the table,
like Name,CreatedDate,CustomField__c." />
<property name="fieldsLabels" label="Fields Labels" type="String"
default="Name,Phone,Created Date"
description="Enter a comma-separated list of field column lables to display in the table,
like Name,Created Date,Custom Field." />
<property name="sObjectName" label="Object Name" type="String" default="Account"
description="Enter the api name of sobject from which you want to show data." />
<property name="urlField" label="Url Field" type="String" default=""
description="Enter the field api name, which you want to show as value in table column,
but want it to redirect to sobject record as a link." />
<property name="allowSorting" label="Allow Sorting" type="Boolean" default="false"
description="Do you need sorting on fields in data table." />
<property name="sortingColumns" label="Column Name to allow sorting" type="String"
default="Name,CreatedDate"
description="Enter a comma-separated list of string of field api name, which should
be allowed for sorting in the table like Name,CreatedDate,CustomField__c." />
<property name="pageSizeOptionsString" label="Page Size Options" type="String"
default="5,10,25"
description="Enter a comma-separated list of string for page size options like 5,10,25." />
<property name="pageSizeDefaultSelectedValue" label="Page Size Default Value"
type="String" default="10"
description="Enter the default page size for table in integer value like 10." />
</targetConfig>
</targetConfigs>
</LightningComponentBundle>
d. Styling with CSS
We will use Salesforce Lightning Design System (SLDS) classes to style our component. In this example, we’ve added the below CSS to static resources.
Static Resource – datatableStyle.css
/* Tabler Header Column Color and css*/
.myTable table > thead .slds-th__action {
background-color: rgba(1, 118, 211, 1) !important;
color: white !important;
font-size: 10px;
font-weight: 700;
width: 75%;
}
/* Tabler Header Column hover color and css*/
.myTable table > thead .slds-th__action:hover {
background-color: rgba(35, 118, 204, 1) !important;
font-size: 10px;
font-weight: 700;
width: 75%;
}
/* overriding data table color and background color*/
.datatable-style {
color: black;
background-color: white !important;
}
/* overriding data table hovor color and background color*/
.datatable-style:hover {
color: black;
background-color: white !important;
}
/* overriding data table special column color and background color*/
.datatable-styleOther {
background-color: white !important;
}
/* overriding data table special column hover color and background color*/
.datatable-styleOther:hover {
background-color: white !important;
}
.slds-is-sortable__icon {
fill: white !important;
}
.dt-outer-container {
padding-left: 10px;
padding-right: 10px;
}
.slds-resizable__divider {
background-color: rgba(35, 118, 204, 1) !important;
}
.noRowHover .slds-truncate {
overflow-wrap: break-word !important;
white-space: pre-line !important;
width: 75%;
}
Apex Class – GenericRecordController
public with sharing class GenericRecordController {
/**
* Retrieves a list of records for a specified sObject
and selected fields.
* @param sObjectName Name of the sObject to query.
* @param fieldNames Comma-separated list of fields to retrieve.
* @return List of sObject records or null if an exception occurs.
*/
@AuraEnabled(cacheable = true)
public static List < sObject > getRecords(String sObjectName,
String fieldNames)
{
try {
// Split the field names by comma and store them in a list
List <String> fields = new List <String> (fieldNames.split(','));
// Get the schema description of the sObject
Schema.DescribeSObjectResult sObjectDescribe =
Schema.getGlobalDescribe().get(sObjectName).getDescribe();
// Check if the user has access to the sObject
if (!sObjectDescribe.isAccessible()) {
throw new AuraHandledException(
'You do not have access to the ' + sObjectName + ' object.'
);
}
// Retrieve the map of fields for the sObject
Map <String, Schema.SObjectField> fieldMap =
sObjectDescribe.fields.getMap();
// Validate each field name for accessibility and existence
for (String fieldName: fields) {
if (!fieldMap.containsKey(fieldName.trim())
&& !fieldName.contains('.')) {
throw new AuraHandledException(
'Invalid field name: ' + fieldName.trim()
);
}
// Check if the user has access to the field (non-relationship fields)
if (!fieldName.contains('.')) {
if (!fieldMap.get(fieldName.trim()).getDescribe().isAccessible()) {
throw new AuraHandledException(
'You do not have access to the ' +
fieldName.trim() +
' field on the ' + sObjectName +
' object.'
);
}
}
}
// Escape single quotes to prevent SOQL injection
String sObjectNameEscaped = String.escapeSingleQuotes(sObjectName);
String fieldNamesEscaped = String.escapeSingleQuotes(fieldNames);
// Construct the SOQL query to retrieve the records
String query =
'SELECT ID, ' + fieldNamesEscaped + ' FROM ' +
sObjectNameEscaped + ' ORDER BY Name LIMIT 2000';
// Execute the query and return the result
return Database.query(query);
} catch (Exception ex) {
// Log the exception for debugging purposes
System.debug(
'exception+++' + ex.getLineNumber() + ' ' + ex.getMessage()
);
return null;
}
}
/**
* Retrieves the data types for specified fields of an sObject.
* @param sObjectName Name of the sObject to query.
* @param fieldNames List of field names to retrieve data types for.
* @return A map of field names to their data types.
*/
@AuraEnabled(cacheable = true)
public static Map <String, String> getFieldTypes(String sObjectName,
List <String> fieldNames)
{
// Retrieve the map of fields for the specified sObject
Map <String, Schema.SObjectField> fieldMap =
Schema.getGlobalDescribe().get(sObjectName).getDescribe().fields.getMap();
// Map to store field names and their data types
Map <String, String> fieldTypes = new Map <String, String> ();
// Iterate through each field name
for (String fieldName: fieldNames) {
// Check if the field exists in the sObject
if (fieldMap.containsKey(fieldName)) {
// Get the field description
Schema.DescribeFieldResult fieldDescribe =
fieldMap.get(fieldName).getDescribe();
// Store the field name and its type in lowercase in the map
fieldTypes.put(
fieldName,
fieldDescribe.getType().name().toLowerCase()
);
}
}
// Return the map of field names and their types
return fieldTypes;
}
}
Usage and Integration
We have built our generic data table LWC component. Now, let’s discuss how to use it and integrate it into a Lightning page.
a. Adding the component to a Lightning page
To add our generic data table LWC to a Lightning app or home page, you need to drag the component. Find it in the Custom Components section. Then drop it into the Lightning App Builder. Once placed, you can configure the component properties as needed.
b. Configuring component properties
After adding the component to your Lightning page, you can configure its properties in the Property Editor. Specify the fields, labels, sObjectName, and other properties according to your requirements. Here’s a quick overview of the properties you can configure:
- Fields: Enter a comma-separated list of field API names to display in the table.
- Fields Labels: Enter a comma-separated list of field column labels to display in the table.
- sObjectName: Enter the API name of the sObject from which you want to fetch data.
- Url Field: Enter the field API name that will be displayed as a value in the table column. It will redirect to the sObject record when clicked.
- Allow Sorting: Toggle this option to enable or disable sorting on the data table.
- Sorting Columns: Enter a comma-separated list of field API names that should be sortable in the table.
- Page Size Options: Enter a comma-separated list of string values for page size options.
- Page Size Default Value: Enter the default page size for the table.
First, configure the component properties. Then, save your changes. Afterward, preview the Lightning page to see your generic data table LWC in action.
Conclusion
In this blog, we’ve explored how to create a feature-rich, generic data table Lightning Web Component in Salesforce. We implemented features such as sorting, clickable URLs, and pagination. As a result, we’ve built a highly customizable and reusable component. It can be easily integrated into any Salesforce application. This LWC component possesses versatile properties. It offers user-friendly configuration options. Therefore, it empowers users to display and analyze their data with ease.
We encourage you to further customize and extend this component to better suit your specific use cases and requirements. Build on the foundation provided in this blog. You can create even more powerful and dynamic data table components. These will enhance your Salesforce applications.
Happy coding!
For more helpful articles please visit – https://thesalesforcedev.wordpress.com/


Leave a comment