Mytutorialrack

Field sets in salesforce

What are field sets in salesforce?

In Salesforce, field sets is a collection of fields on an object that you can group together and reference in various ways. It provides a way to define a set of fields that you can reuse in multiple places, such as in Apex, Visualforce pages, and LWC components.

Benefits of using Field Sets in Salesforce

  1. Reusability: You can define a field set once and use it in multiple contexts, reducing redundancy and making maintenance easier. This is especially useful when you have multiple Visualforce (vf) pages or components that need to display the same set of fields.
  2. Dynamic behavior: Field sets enable dynamic behavior because they are customizable at runtime. You can add or remove fields from a field set without modifying the underlying code, making it easier to adapt to changing requirements.
  3. Efficient development: Developers can use field sets in their Apex code to iterate over the fields in a set, which can simplify development and reduce the amount of code needed to work with a set of fields.

Salesforce Field Sets : How to Create a Field Set in Salesforce?

  • Step 1: Access the Object Setup Page: Navigate to the object for which you want to create a field set. In Salesforce, go to the Setup page and search for the object in the Quick Find box. Click on the object name to access its setup page.
  • Step 2: Locate the “Fields & Relationships” Section: On the object’s setup page, find the “Fields & Relationships” section.
  • Step 3: Find the “Field Sets” Option Within the “Fields & Relationships” section, locate the “Field Sets” option.
  • Step 4: Create a New Field Set Click on the “Field Sets” option to access the field set management page. Here, you can view existing field sets or create a new one. Look for the option to create a new field set and click on it.
  • Step 5: Define the Field Set In the field set creation interface: you can specify the desired fields that you want to include in the set. You can typically drag and drop fields from a list or use checkboxes to select the fields. Give your field set a descriptive name to easily identify its purpose.
  • Step 6: Save the Field Set : Once you have selected the desired fields for your field set, click the “Save” or “Save Field Set” button to save your changes. The field set will now be created and available for use.
  • Step 7: Utilize the Field Set :After creating the field set, you can reference it in various parts of the Salesforce platform.

Create a Field Set on Account

  1. Log in to your Salesforce org and navigate to the setup page.
  2. Search for and select the “Object Manager” tab.
  3. Find and click on the “Account” object.
  4. In the left sidebar, under “Fields & Relationships,” click on “Field Sets.”
  5. Click on the “New Field Set” button.
  6. Give the field set a name, such as “AccountFieldSet” or any other name you like.
  7. In the “Available Fields” section on the right, you will see a list of fields available for the “Account” object.
  8. Select the fields you want to include in the field set. For example, you can choose “Account Name,” “Industry,” and “Annual Revenue” by clicking the checkbox next to each field.
  9. Click the “Add to Field Set” button to add the selected fields to the field set.
  10. You can reorder the fields within the field set by dragging and dropping them.
  11. Click the “Save” button to save the field set.

How to use field sets in Apex? 

In Apex, you can use a field set to dynamically retrieve and work with a set of fields on an object. Here’s an example of how to use a field set in Apex: (Run the code in Anonymous Block)

// Define the object and field set API names
String objectAPIName = 'Account';
String fieldSetName = 'AccountFieldSet';

// Get the field set information
Schema.SObjectType objectType = Schema.getGlobalDescribe().get(objectAPIName);
Schema.DescribeSObjectResult objectDescribe = objectType.getDescribe();
Schema.FieldSet fieldSet = objectDescribe.fieldSets.getMap().get(fieldSetName);

// Retrieve the field set fields
List<Schema.FieldSetMember> fieldSetMembers = fieldSet.getFields();

// Create a dynamic query to fetch the fields specified in the field set
String query = 'SELECT ';
for (Schema.FieldSetMember fieldSetMember : fieldSetMembers) {
    query += fieldSetMember.getFieldPath() + ', ';
}
query = query.removeEnd(', ') + ' FROM ' + objectAPIName;

// Execute the query
List<SObject> records = Database.query(query);

// Iterate over the records and access the field values dynamically
for (SObject record : records) {
    for (Schema.FieldSetMember fieldSetMember : fieldSetMembers) {
        String fieldAPIName = fieldSetMember.getFieldPath();
        Object fieldValue = record.get(fieldAPIName);
        System.debug('Field: ' + fieldAPIName + ', Value: ' + fieldValue);
    }
}

Here is the outcome of the above code :

How to use Field Sets in Visualforce page?

Assuming we have an “Contact” object and a field set named “ContactFieldSet” that includes the fields “First Name,” “Last Name,” “BirthDate” , “Account Name” and “Contact Id,” here’s how you can use the field set in a Visualforce page:

  1. Create a new Visualforce page (e.g., “ContactPage”) and associate it with a controller or controller extension that retrieves the Contact records.
  2. In the Visualforce page, use the <apex:pageBlockSection> component to display the fields specified in the field set.

Here’s an example Visualforce page implementation:

<apex:page standardController="Contact">
  <apex:form >
      <apex:pageblock >    
          <apex:pageBlockSection title="Contact detail">
             <apex:repeat value="{!$ObjectType.Contact.fieldsets.contactFieldSet}" var="fieldValue">
                 <apex:Inputfield value="{!Contact[fieldValue]}"/>
             </apex:repeat>
          </apex:pageBlockSection>
      </apex:pageblock>
    </apex:form>
</apex:page>

Here is another example of using Field set in a Visualforce page with FieldSet on Account

In this example, we will be using AccountFieldSet that we have created earlier. We will use the field set inside of a visualforce page.

AccountVfp

<apex:page controller="AccountController">
   <apex:pageBlock>
      <apex:pageBlockTable value="{!accounts}" var="account">
         <apex:repeat value="{!fieldSetMembers}" var="field">
            <apex:column headerValue="{!field.Label}">
               {!account[field.FieldPath]}
            </apex:column>
         </apex:repeat>
      </apex:pageBlockTable>
   </apex:pageBlock>
</apex:page>

AccountController

public class AccountController {
public List<Account> accounts { get; set; }
   public List<Schema.FieldSetMember> fieldSetMembers { get; set; }
   
   public AccountController() {
      // Retrieve the field set information
      Schema.SObjectType accountType = Schema.getGlobalDescribe().get('Account');
      Schema.DescribeSObjectResult accountDescribe = accountType.getDescribe();
      Schema.FieldSet fieldSet = accountDescribe.fieldSets.getMap().get('AccountFieldSet');
      fieldSetMembers = fieldSet.getFields();
      String queryString = 'SELECT Id';
        List<Account> accList = new List<Account>();
        for(Schema.FieldSetMember fld :fieldSetMembers) {
            queryString += ', ' + fld.getFieldPath();
        }
        queryString += ' FROM Account LIMIT 10';
         
        accounts = Database.query(queryString);
        
   }

}

How to use Fields Sets in Lightning Web Component (LWC)

In this example, we will use the ContactFieldSet that we created previously and we will utilize in our Lightning Web Component.

public class ContactFieldSetController {
@AuraEnabled(cacheable=true)
    public static List<Contact> fetchContactFieldSetData(){
        String queryString = 'SELECT Id';
        List<Contact> conList = new List<Contact>();

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

        queryString += ' FROM Contact LIMIT 10';
         
        conList = Database.query(queryString);
        return conList;
    }

    @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+']';
    }
}

contactLWC.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>How to use Field Sets in LWC</span>
                                        <span class="slds-page-header__title slds-truncate" title="Recently Viewed">Mytutorialrack</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 Example" 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>

contactLWC.js

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

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

    @wire(getFieldSet, { sObjectName: 'Contact', fieldSetName: 'ContactFieldSet' })
    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(fetchContactFieldSetData, {})
    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;
    }
}

contactLWC.js-meta.xml

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

Once this LWC component is ready, you can add this component to your HOME PAGE and see the magic of Field Sets.

Things to Keep in mind regarding Field Sets

  1. Plan and design field sets:
    • Determine the specific use cases and requirements for each field set.
    • Design field sets with reusability in mind.
  2. Use descriptive names:
    • Provide clear and meaningful names for your field sets.
    • Follow a consistent naming convention.
  3. Regularly review and update field sets:
    • Periodically review field sets to ensure they align with current requirements.
    • Remove any unused or unnecessary fields from field sets.
  4. Handle field-level security:
    • Ensure that the fields included in field sets respect field-level security settings.
  1. Optimize performance:
    • Include only the necessary fields in field sets to avoid performance issues.
    • Be mindful of the number of fields included in queries.
  2. Document field set usage:
    • Maintain documentation or metadata about the usage of field sets.
    • Document which components utilize specific field sets and provide explanations or guidelines for their usage.
  3. Test thoroughly:
    • Conduct comprehensive testing to ensure proper functionality when using field sets.
    • Test different scenarios, including dynamic changes to field sets.
  4. Leverage field sets in multiple contexts:
    • Utilize field sets across different Salesforce components, such as Visualforce pages, LWC and Apex code.
    • Promote reusability and consistency.
  5. Follow coding best practices:
    • When using field sets in Apex code, adhere to coding best practices.
    • Bulkify your code, handle exceptions, and write efficient queries.

This blog post has provided you with all the information related to Salesforce Field Sets. We have talked about field sets, how to create field sets, and how to use the field sets in vf pages, apex, and LWC components. If you have enjoyed the post, please share the post on LinkedIn.

Share:

Recent Posts