Wednesday, 14 October 2015

How to dynamically retrieve list of fields based on object name in salesforce

Apex Class:

  1. public class FieldListController
  2. {
  3.     public static void fetchFields(String objectName)
  4.     {
  5.         List<SelectOption> fieldList = new List<SelectOption>();
  6.         Map<String , Schema.SObjectType> describeSObject = Schema.getGlobalDescribe();
  7.         Schema.sObjectType objType = describeSObject.get(objectName);
  8.        
  9.         if(objType != null)
  10.         {
  11.             Schema.DescribeSObjectResult desResult = objType.getDescribe();
  12.             Map<String, Schema.SObjectField> fieldMap = desResult.fields.getMap();  
  13.            
  14.             for(Schema.SObjectField currField : fieldMap.values())  
  15.             {  
  16.                 Schema.DescribeFieldResult fieldResult = currField.getDescribe();  
  17.  
  18.                 if(fieldResult.isAccessible())  
  19.                 {  
  20.                     fieldList.add(new SelectOption(fieldResult.getLabel(), fieldResult.getLabel()));
  21.                 }
  22.             }
  23.        
  24.             System.debug('### Field List Controller'+fieldList);
  25.         }
  26.     }
  27. }


Run From Developer Console:

Pass the object API Name in the below method,

FieldListController.fetchFields('Account');

No comments:

Post a Comment

Activities: Assign Tasks to a Queue Salesforce Lightning

Salesforce announced to assign Tasks to a Queue beginning from Spring'20 release. How does it work? In Setup, enter Queues in th...