Target Audience
The target audience for this article is someone who has basic knowledge about apex in Salesforce.
Perquisite
Basic knowledge of apex
Learning dynamic apex helps you to become a better programmer and also it is common question asked in interviews. However, there are not much articles written on this topic. After going through this article, you will get an understanding of dynamic apex and how to use it.
Let’s get Started
Let’s dive into advance topic in Apex i.e. Dynamic Apex. However, don’t worry I will be explaining you the concepts to make your learning journey easier. So lets get started.
The first question is what is Dynamic Apex and how is it helpful ? Dynamic apex help developers to create more flexible applications by providing them with the ability to access sObject and field metadata description,access salesforce app information, write dynamic SOQL queries, dynamic SOSL queries and dynamic DML.
Confused with the definition? I was too when I first read it. Let’s try to understand it in simple terms by breaking down the definition into smaller parts.
1. Ability to access sObject and field metadata description
Sobject are all the standard and custom objects that are stored in Force.com platform database.For eg, standard objects like account, contact and custom object like camping__c are all sobjects. So dynamic apex helps in providing information like whether sObject supports operations like create or undelete, the sObject’s name and label etc.
Schema.getGlobalDescribe() : Returns map of all Sobjects names( Keys) to sObject tokens (values) for the standard and custom objects defined in the organization.
Token is the API name for the sobject. It consumes very little resources, as compared to a describe, because it doesn’t actually contain any information about the field or object, such as its label, data type, maximum length, etc.
Lets understand it more clearly by seeing workbench. In Map< String, Schema.SobjectType> String contains object name and schema.sobjectType contains object properties/attributes.
The describe information for a field includes whether the field has a default value, whether the field is createable, filterable, groupable etc.
Lets understand it more clearly by seeing workbench. In Map< String, Schema.SobjectField> String contains Field name and schema.sobjectField contains Field properties/attributes.
2. It helps in accessing Salesforce app information.
You can obtain describe information for standard and custom apps available in the Salesforce user interface. Each app corresponds to a collection of tabs. Describe information for an app includes the app’s label, namespace,tabs etc.
Example: Description=The world’s most popular sales force automation (SFA)solution, Label=Sales
Write dynamic SOQL queries, dynamic SOSL queries and dynamic DML.
Write dynamic SOQL queries, dynamic SOSL queries and dynamic DMLDynamic SOQL and SOSL queries provide the ability to execute SOQL or SOSL as a string at runtime.
Dynamic SOQL refers to the creation of a SOQL string at run time with Apex code
Dynamic SOSL refers to the creation of a SOSL string at run time with Apex code
Dynamic DML creates sObjects dynamically, and insert them into the database using DML.
Enough of theory, now lets do some examples to understand dynamic apex clearly.
Example: Access field description information for accounts
Map<String,Schema.SObjectType> m = Schema.getGlobalDescribe(); Schema.SObjectType s = m.get('Account'); Map<String,schema.SObjectField> mapField = s.getDescribe().fields.getMap(); system.debug(mapField.keyset()); system.debug(mapField.values());
Example: Get all the fields of sObject using Dynamic Apex
Map<String,Schema.SObjectType> m = Schema.getGlobalDescribe(); for(Schema.SObjectType s: m.values()){ Map<String,schema.SObjectField> mapField = s.getDescribe().fields.getMap(); system.debug(mapField.keyset()); system.debug(mapField.values()); }
Example: Access all sObjects and field describe information:
Map<String,Schema.SObjectType> m = Schema.getGlobalDescribe(); map<Schema.SObjectType,Map<String,schema.SObjectField>> newmap=new map<Schema.SObjectType,Map<String,schema.SObjectField>>(); for(Schema.SObjectType s: m.values()){ Map<String,schema.SObjectField> mapField = s.getDescribe().fields.getMap(); newmap.put(s,mapField); } for(Schema.SObjectType s: m.values()){ Map<String,schema.SObjectField> newmap1=newmap.get(s); system.debug(s); system.debug(newmap1); }
Example: Access all the objects which are creatable
Map<String,Schema.SObjectType> m = Schema.getGlobalDescribe(); for(Schema.SObjectType st:m.values()){ Schema.DescribeSobjectResult objResult = st.getDescribe(); Map<Schema.SObjectType,boolean> ObjectCreatable = new Map<Schema.SObjectType,boolean>(); ObjectCreatable.put(st,objResult.isCreateable()); system.debug(ObjectCreatable); }
Example: Use SOQL query to fetch all fields of account object
String SobjectApiName = 'Account'; Map<String,Schema.SObjectType> schemaMap = Schema.getGlobalDescribe(); Map<String,schema.SObjectField> fieldMap = schemaMap.get(SobjectApiName).getDescribe().fields.getMap(); String commaSepratedFields = ''; for(String fieldName : fieldMap.keyset()){ if(commaSepratedFields == null || commaSepratedFields == ''){ commaSepratedFields = fieldName; }else{ commaSepratedFields = commaSepratedFields + ', ' + fieldName; } } string query = 'select ' + commaSepratedFields + ' from ' + SobjectApiName + ' Limit 5'; List accList = Database.query(query); system.debug(accList);
Hopefully, the explanation and scenarios will help in clearly understanding dynamic apex. For more of these kind of articles stay tuned. Happy Coding!
References:
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_dynamic.htm
Thanks smiriti.Very well explained with example,highly appreciated.
Thanks a lot