How to create and use FieldSet in Salesforce

|
| By Webner

How to create and use FieldSet of a particular Object (Standard or Custom) in Salesforce

FieldSets are commonly used where we want to display fields of a particular object in the Visualforce page dynamically.

1. Steps to create FieldSet of a particular Object:
Open Layout of any Object(Standard/Custom). Then click on New button in the FieldSet. Then It’ll open the following window:

Suppose I’ve created a FieldSet named as “contactFieldSet” in the Contact Standard Object and added some fields in this fieldSet as shown below image:

Click on Save button to save this FieldSet.



2. How to access FieldSet in apex class:
Code below will fetch the list of all the fields that are present in the fieldSet:

List<Schema.FieldSetMember>conFieldList= SObjectType.Contact.FieldSets.contactFieldSet.getFields();

Here, Contact = Object API Name
contactFieldSet = Name of the FieldSet of a particular object.

b. By looping through the fieldSet List that we fetched from above code, we can get the label, API Name and Type of each field in the FieldSet as shown below:

for(Schema.FieldSetMember field : conFieldList) {
      system.debug(field.getFieldPath());
      system.debug(field.getLabel());
      system.debug(field.getType());
}

Below are the methods to get the label, API Name and Type of each field in the FieldSet:

  • getFieldPath() = This method is used to get API Name of a field.
  • getLabel() = This method is used to get Label of a field.
  • getType() = This method is used to get Datatype of a field.

Leave a Reply

Your email address will not be published. Required fields are marked *