Tuesday, February 5, 2019

How to query fields which are in the fieldset using SOQL in Salesforce.

Hi all,
Today I am going to explain to you that how can you query all fields from fieldset.
Suppose you have created one fieldset in Contact object and you have also added some fields in that fileldset like this.

How to create fieldset in Salesforce?
Steps

  1. Enter your object name in the setup and click on fieldset.
  2. Click on New and enter details like it's label, API name etc.
  3. Click on save and then you will be redirected to on page where you can drag and drop all the fields which you want that should be in the fieldset.
So you are done with your fieldset and also you have added some fields to fieldset as well.
Now let's move to the next step.
So now you have two things

  1. Object API Name : Contact
  2. FieldSet API Name: testingFieldsetName (It will be same what you provide while creating fieldset)
Here is the code that will be used to query all fields available in the fieldset.


  String objectApiName = 'Contact';
String fieldSetName = 'testingFieldsetName';
       
//Get the fields from FieldSet
Schema.SObjectType sObjectTypeObj = Schema.getGlobalDescribe().get(objectApiName);
Schema.DescribeSObjectResult describeSObjectResultObj = sObjectTypeObj.getDescribe();           
Schema.FieldSet fieldSetObject = describeSObjectResultObj.FieldSets.getMap().get(fieldSetName);
      
//Field to be queried - fetched from fieldset
List<String> fieldsToQueryList = new List<String>();
       
for( Schema.FieldSetMember eachFieldSetMember : fieldSetObject.getFields() ){
    fieldsToQueryList.add(String.valueOf(eachFieldSetMember.getFieldPath()));
}
       
String query = 'SELECT '+ String.join(fieldsToQueryList , ',') + ' FROM CONTACT';
List<Contact> contactsList =  Database.query(query);
  
Hope this post helps you.