SalesforceBlue

Feel the rhythm of Salesforce

Apex

Dynamic Apex Simplified

Dynamic apex assists developers to write more flexible and dynamic applications. They are handy for situations when you wanted to write a dynamic query, wanted to access properties of an object on run time, and then take specific actions, etc.

We can write Dynamic Apex in the following ways:

Schema Describe:

Schema Describe allows us to dynamically discover the names, properties of objects, and fields in the org. Schema class provides us with several methods which are used to make describe calls.

Schema.getGlobalDescribe():

Map<String, Schema.SObjectType> globalDescribe = Schema.getGlobalDescribe();

It returns a map of all sObject names(keys) to sObject tokens(values) for the standard and custom objects defined in an org.

Describe Result:

An object that contains all the describe properties for the sObject or field.

Schema.SObjectType:

It is the data type of a sObject token.

Schema.SObjectField:

It is the data type of a field token.

Token:

It is a lightweight reference to a sObject or a field. Tokens have the getDescribe() methods which return the describe result object.

Schema.DescribeSObjectResult:

Returned by doing a getDescribe() call from a sObject token. An object that contains all the describe properties for the sObject.

Schema.ChildRelationship and Schema.RecordTypeInfo objects can be retrieved by an instance of Schema.DescribeSObjectResult.

Schema.DescribeFieldResult:

Returned by doing a getDescribe() call from a field token. An object that contains all the describe properties for the field.

Let’s see schema describe calls in action:

public class BlueUtility {
    public static void describeCalls() {

        // Generate a map of all sObject names to sObject tokens.
        Map<String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();

        // Declaring a string to hold the name of the object. 
        String objectName = 'Contact';

        // Get the DescribeSObjectResult for the arbitary object. 
        Schema.DescribeSObjectResult dsr = schemaMap.get(objectName).getDescribe();

        // Generate a Map of all field names to field tokens.
        Map<String, Schema.SObjectField> fieldMap = dsr.fields.getMap();

        // Declaring a String to hold the field Name 
        String fieldName = 'LeadSource';

        // Get the DescribeFieldResult of the fieldname.
        Schema.DescribeFieldResult dfr = fieldMap.get(fieldName).getDescribe();

        // Get the Schema.PickListEntry list from the DescribeFieldResult
        List<Schema.PicklistEntry> picks = dfr.getPicklistValues();
    }
}

In the above code block, the below steps are performed to get the describe results of a field token:

  1. Do a global describe.
  2. Make a object map using the result of global describe
  3. Get the object token from the object map.
  4. Make a describe result call on the object token.
  5. Get the field token from the field map.
  6. Make a describe result call on the field token.

The above approach takes a good amount of CPU processing time. A better alternative approach to getting describe results for the field is mentioned below:

SObjectType sObj = ((SObject)Type.forName('Schema',objectAPIName).newInstance()).getSObjectType();

Map<String,Schema.SObjectField> mapFieldMetaData= sObj.getDescribe().SObjectType.getDescribe().fields.getMap();
Dynamic SOQL:

It allows you to Query for data by creating a dynamic query string and not hardcoding the names and objects in the SOQL statements.

 String queryString = 'Select Id, Name From Account';
 List<Account> accouuntList = Database.query(queryString);
Dynamic SOSL:

It allows you to search for data by creating a dynamic query string and not without hardcoding the names of fields and objects in the SOSL statements.

String email = 'salesforceblue@gmail.com';
String queryString = '[FIND :'+ email +' IN ALL FIELDS RETURNING Contact (Id, Name), Lead(Id, Name)]';
List<List<sObject>> searchList = search.query(SOSL_query_string);
Dynamic DML:

Manipulating data dynamically without hardcoding the object type and field names.

Below is a generic method that accepts any object, a field to modify and a respective value to set.

 public void recordToModify(sObject recordToUpdate, String fieldToModify, String valueToPut){
        recordToUpdate.put(fieldToModify, valueToPut);
        update recordToUpdate;
    }

Thank you for visiting SalesforceBlue.com
If you have any queries feel free to write down a comment below 🙂


Leave a Reply

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