Field Set in Apex LWC Salesforce

by Rijwan Mohmmed
0 comment
field-set-in-apex-lwc-salesforce

Hello folks, today we are going to discuss Field Set in Apex LWC Salesforce. An object’s field set is a grouping of fields. We can use dynamic bindings to display field sets on our LWC component. When we are working with managed packages, FieldSet is very useful. We can query the field sets in SOQL and show the data on LWC. Therefore, we’ll use a dynamic SOQL query to query all fields in the FieldSet. In this way, our code will be dynamic.

Also check this: Future Methods in Apex Salesforce

Key Highlights :

  1. Fieldset changes do not require code modifications.
  2. Fieldset is a grouping of fields of an Object.

Code & Process :

Step 1: Navigate to Setup > Object Manager > Account > Fieldset

Navigate-to-fieldset-Techdicer
Navigate-to-fieldset-Techdicer

Step 2: Create Field Set record

Create-fieldset-record-in-Object
Create-fieldset-record-in-Object

Step 3: Now we will drag-drop the field in field set section.

drag-drop-fieldset-fields
drag-drop-fieldset-fields

AccountFieldSetCtrl.cls :

public class AccountFieldSetCtrl {

    @AuraEnabled(cacheable=true)
    public static List<Account> fetchAccountFieldSetData(){
        String queryString = 'SELECT Id';
        List<Account> accList = new List<Account>();

        for(Schema.FieldSetMember fld :SObjectType.Account.FieldSets.Account_Field_Set.getFields()) {
            queryString += ', ' + fld.getFieldPath();
        }

        queryString += ' FROM Account LIMIT 10';
         
        acclist = Database.query(queryString);
        return acclist;
    }

    @AuraEnabled(cacheable=true)
    public static String getFieldSet(String sObjectName, String fieldSetName) {
        String result = '';
        try{
            SObjectType objToken = Schema.getGlobalDescribe().get(sObjectName);
            Schema.DescribeSObjectResult d = objToken.getDescribe();
            Map<String, Schema.FieldSet> fieldSetMap = d.fieldSets.getMap();

            if(fieldSetMap.containsKey(fieldSetName)){
                for(Schema.FieldSetMember f : fieldSetMap.get(fieldSetName).getFields()) {
                     
                    if(String.isNotBlank(result)){
                        result += ',';
                    }

                    String jsonPart = '{';
                    jsonPart += '"required":"' + (f.getDBRequired() || f.getRequired()) + '",';
                    jsonPart += '"type":"' + (f.getType()) + '",';
                    jsonPart += '"label":"' + (f.getLabel()) + '",';
                    jsonPart += '"name":"' + f.getFieldPath() + '"';
                    jsonPart += '}';
                    result += jsonPart;
                }
            }
        }
        catch(Exception ex){
            result += ex.getLineNumber() + ' : ' + ex.getMessage();
        }
        return '['+result+']';
    }
}

accountFieldSetLWC.HTML:

<template>
	<!--------card header ----------------->
	<div class="slds-tabs_card">
		<div class="slds-page-header">
			<div class="slds-page-header__row">
				<div class="slds-page-header__col-title">
					<div class="slds-media">
						<div class="slds-media__figure">
							<span class="slds-icon_container slds-icon-standard-opportunity">
                                 <lightning-icon icon-name="standard:recipe" alternative-text="recipe" title="recipe"></lightning-icon>
                            </span>
						</div>
						<div class="slds-media__body">
							<div class="slds-page-header__name">
								<div class="slds-page-header__name-title">
									<h1>
										<span>Field Set in Apex LWC Salesforce</span>
										<span class="slds-page-header__title slds-truncate" title="Recently Viewed">TechDicer</span>
									</h1>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div> <br/>
	<!--------/card header end ----------------->
	<!------ Custom Datatable with field set ------------------------->
	<lightning-card variant="Narrow" title="Field Set in Apex LWC Salesforce" icon-name="standard:apps">
		<div class="slds-p-horizontal_small" if:true={isColumnsDataAvailable}>
			<lightning-datatable key-field="id" data={data} columns={columns}>
			</lightning-datatable>
		</div>
	</lightning-card>
	<!------ /Custom Datatable with field set ------------------------->
</template>

accountFieldSetLWC.JS:

import { LightningElement, track, wire } from 'lwc';
import fetchAccountFieldSetData from '@salesforce/apex/AccountFieldSetCtrl.fetchAccountFieldSetData';
import getFieldSet from '@salesforce/apex/AccountFieldSetCtrl.getFieldSet';

export default class AccountFieldSetLWC extends LightningElement {
    @track data;
    @track columns;
    @track error;

    @wire(getFieldSet, { sObjectName: 'Account', fieldSetName: 'Account_Field_Set' })
    wiredFields({ error, data }) {
        if (data) {
            data = JSON.parse(data);
            console.log(data);
            let cols = [];
            data.forEach(currentItem => {
                let col = { label: currentItem.label, fieldName: currentItem.name };
                cols.push(col);
            });
            this.columns = cols;
        } else if (error) {
            console.log(error);
            this.error = error;
            this.columns = undefined;
        }
    }

    @wire(fetchAccountFieldSetData, {})
    wiredAccounts({ error, data }) {
        if (data) {
            this.data = data;
            console.log(this.data);
        } else if (error) {
            console.log(error);
            this.error = error;
            this.data = undefined;
        }
    }

    get isColumnsDataAvailable() {
        return this.data && this.columns;
    }
}

accountFieldSetLWC.js-meta.xml:

<?xml version="1.0"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
	<apiVersion>55.0</apiVersion>
	<isExposed>true</isExposed>
	<targets>
		<target>lightning__HomePage</target>
	</targets>
</LightningComponentBundle>

Output :

field-set-in-apex-lwc-salesforce-output-techdicer
field-set-in-apex-lwc-salesforce-output-techdicer

Reference :

  1. FieldSet

You may also like

Leave a Comment