What is FieldSet?
An object's fields are organized into sets called Fieldset. This is applicable to the LWC component, Apex class, and Visualforce page. The VF Page/LWC component's Field Set feature allows us to dynamically add, remove, and reorganize the fields without changing the component's code.
How to create a FieldSet?
Go to setup and open object Manager and select the object in which you want to create a fieldset.
Click on fieldSet then click on the New button to create a new Fieldset.
Now fill up the following information to create a fieldset.
After clicking on the save button fieldset will be created.
Now click on your fieldset and start adding fields that you want to show in the Table. There are two options to add fields, we need to add “In the field set” as shown in the below image. Save it!!
If a custom controller is being used, a SOQL query may require to query fieldset fields. Therefore, to query all of the fields in the fieldset, we will apply a dynamic SOQL query.
As a result, our code will become dynamic as we are using a dynamic SOQL query and fieldset. No more changes to our code are required. The fields in the fieldset can be added, removed, or rearranged with ease. The modifications will be automatically reflected.
AccountDomainFieldSet -
public with sharing class AccountDomainFieldSet {
@AuraEnabled(Cacheable = true)
//Creating a queryString where we add fields name as per FieldSet and fetch accounts as per queryString.
public static List<Account> getAccount() {
try {
String queryString = 'select id';
for (Schema.FieldSetMember fieldSet : SObjectType.Account.FieldSets.Account_Field_Set.getFields()) {
queryString += ',' + fieldSet.getFieldPath();
}
queryString += ' from Account limit 100';
return Database.query(queryString);
} catch (Exception e) {
throw new AuraHandledException(e.getMessage());
}
}
@AuraEnabled
// Create Map of Label and fieldName to use this map in columns of datatable
public static string getFieldLableAndFieldAPI(){
List<Map<String ,String>> listOfFieldSet = new List<Map<String ,String>>();
try {
for(Schema.FieldSetMember fieldset : SObjectType.Account.FieldSets.Account_Field_Set.getFields()) {
Map<String ,String> lableAPIMap = new Map<String ,String>();
lableAPIMap.put(fieldset.getLabel(),fieldset.getFieldPath());
listOfFieldSet.add(lableAPIMap);
}
} catch (Exception e) {
throw new AuraHandledException(e.getMessage());
}
return JSON.serialize(listOfFieldSet);
}
}
AccountControllerFieldSet-
public with sharing class AccountControllerFieldSet {
@AuraEnabled(cacheable=True)//Get Account Records
public static List<Account> getAccountList(){
return AccountDomainFieldSet.getAccount();
}
}
Now, We will create an LWC Component “fieldsetWithDatatable”
fieldsetWithDatatable.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>55.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
</targets>
</LightningComponentBundle>
fieldsetWithDatatable.html
<template>
<lightning-card title={title}>
<template if:true={checkFieldSet}>
<lightning-datatable key-field="id" data={data} columns={columns}>
</lightning-datatable>
</template>
</lightning-card>
</template>
fieldsetWithDatatable.js
import {LightningElement, wire} from 'lwc';
import title from '@salesforce/label/c.FieldSet_example_with_datatable';
import getAccount from '@salesforce/apex/AccountControllerFieldSet.getAccountList';
import getFieldLableAndFieldAPI from '@salesforce/apex/AccountDomainFieldSet.getFieldLableAndFieldAPI';
import {ShowToastEvent} from 'lightning/platformShowToastEvent';
export default class FieldSetWithDatatable extends LightningElement {
title = title;
checkFieldSet= false;
columns =[];
data = [];
dataIsPresent = false;
connectedCallback(){
this.handleClick();
}
@wire(getAccount)
accountData({data, error}){
if(data){
this.data = data;
this.dataIsPresent = true;
}
else if(error){
this.showError(error);
}
}
handleClick(){
getFieldLableAndFieldAPI()
.then((data) =>{
let fieldSet = JSON.parse(data);
this.columns.push({label : "Account Id", fieldName : "Id"});
for (let index = 0; index < fieldSet.length; index++) {
this.columns.push({label : Object.keys(fieldSet[index])[0], fieldName : Object.values(fieldSet[index])[0]});
}
this.checkFieldSet = true;
})
.catch((error) => {
this.showError(error);
});
}
showError(error){
const event = new ShowToastEvent({
title: 'Error',
message: error
)};
this.dispatchEvent(event);
}
}
Output-
Now, If you want to add/remove any fields in the fieldset then it will automatically update to this table.
In our case, We remove the “Account Rating” field from the fieldset and add the “Created By” field in the fieldset also you can reorder according to your requirement
This is the final output after adding and removing the fields -
Happy!! to help you add to your knowledge. You can leave a comment to help me understand how the blog helped you. If you need further assistance, please contact us. You can click "Reach Us" on the website and share the issue with me.
Blog Credit:
N. Mehra
S. Chaudhary
Salesforce Developer
Avenoir Technologies Pvt. Ltd.
Reach us: team@avenoir.ai
Are you in need of Salesforce Developers?