Dynamic Apex

Dynamic Apex enables developers to create more flexible application.

1. Access sObject and Fields Describe information.

This part of programming is called as schema programming. We have predefined class and methods in salesforce to describe sObjects and fields. “Describe the sObjects” means knowing the metadata information about the sObject such as type of object, label, the object’s fields etc., Similarly describe information for a field includes the information as if the field has a default value, whether it is a calculated field, type of field and so on.

2. Access Salesforce App information

As describe the sObject, we have can obtain describe information about the salesforce apps (standard or custom). This includes the various metadata information about the app such as label, tabs, namespace and so on..

3. Dynamic SOQL or SOSL

This enable us to execute the SOQL or SOSL as a string during run time. Based on an user input, we can build the query and execute the same as a string with the help of predefined database methods. This can be useful for applications that are installed from Force.com AppExchange.

How to get describe information for sObject and fields?.

1. Using Token – it is a reference to an sObject or a field validated at a compiled time. This token can be described using predefined classes and methods.
2. describeSObjects method – This is a method belong to predefined class Schema that performs describes on one or more sObject types. In either cases above, an object of type Schema.DescribeSObjectResult can be used to refer all the properties for the sObject and fields described from tokens or describeSObject method.

Steps to obtain describe information.

1. Generate list or map of tokens for the sObjects
2. Determine the sObject type
3. Get the describe result
1. Similarly if required generate map of field tokens for the sObject.
2. Describe the above tokens.

How to describe sObject using tokens?

SObjects, such as Account and MyCustomObject__c, act as static classes with special static methods and member variables for accessing token and describe result information
1. Generate token.
For account sObject.
sObjectType is a static member of class Account. This static member will return a value of data type -Schema.sObjectType.

Schema.sObjectType t = Account.sObjectType;

The following also returns a token for the Account sObject:

Account a = new Account();
Schema.sObjectType t = a.getSObjectType();

2. Obtain the describe information from the above token using the getDescribe() method belong to Schema Namespace.

Schema.DescribeSObjectResult ObjResult = t.getDescribe();
System.debug('Describe Info about Account ' + ObjResult);
//the above statments of generating token and describe the token can be replaced with single statement below
Schema.DescribeSObjectResult ObjResult1 = Account.sObjectType.getDescribe();

Similarly how to create Field Tokens and get describe info?

There are two ways.
1. Access the static member variable name of an sObject static type, for example, Account.Description.

Schema.sObjectField fieldToken = Account.Description;
Schema.DescribeFieldResult fieldResult = fieldToken.getDescribe();
System.debug('field describe info ' + fieldResult);

2. Call the getSObjectField method on a field describe result.

// Get the describe result for the Name field on the Account object
Schema.DescribeFieldResult dfr = Schema.sObjectType.Account.fields.Name;
// Verify that the field token is the token for the Name field on an Account object
System.assert(dfr.getSObjectField() == Account.Name);
// Get the describe result from the token
dfr = dfr.getSObjectField().getDescribe();

Example for Description field

Schema.DescribeFieldResult fieldResult1 = Schema.sObjectType.Account.fields.Description;
System.debug('field describe info ' + fieldResult1);

Accessing All Field Describe Results for an sObject:
Use the field describe result’s getMap method to return a map that represents the relationship between all the field names (keys) and the field tokens (values) for an sObject.

Map<String, Schema.SObjectField> fieldMap = Schema.sObjectType.Account.fields.getMap();
//Get the keys (field names) from the map fieldMap 
System.debug(fieldMap.keySet());
//Get the tokens from the above map.
System.debug(' describe info for industry field ' + fieldMap.get('Industry').getDescribe());

So far we have seen about how to describe a sObject. Now will see how to obtain describe info for all sObjects?

Use getGlobalDescribe() method of Schema Class. This method will return the sObject names as string and corresponding tokens.
 

Map<String, Schema.sObjectType> mapObjects = Schema.getGlobalDescribe();

//To get the object names (keys)
System.debug('List of sObjects from my org ' + mapObjects.keySet());

//iterate the map and display the object name one by one
Set<String> objectNames = mapObjects.keySet();
system.debug('Total no of sObjects ' + objectNames.size());

for(String ob : objectNames){
   System.debug(ob);
}

OR

for(String ob1 :mapObjects.keySet()){
   System.debug(obj1);
}

OR

for(String ob: Schema.getGlobalDescribe().KeySet()){
   System.debug(ob);
}

How to obtain sObject describe information?
1. Use Token and describe (using getDescribe())
We have seen examples for this approach earlier.

2. Schema Method – describeSObjects (specified object or array of objects)

String[] objNames = new String[]{'Account', 'Position__c'};
Schema.DescribeSObjectResult[] objResults =  Schema.describeSObjects(objNames);
//system.debug(objResults[0]);

for(Schema.DescribeSObjectResult sd: objResults){
        System.debug('sObject Label ' + sd.getLabel());
        System.debug('Is Custom Obj? '+ sd.isCustom());
        Schema.ChildRelationship[] childs = sd.getChildRelationships(); //refer the methods below
        System.debug(sd.getName() + ' has ' + childs.size() + ' chilsd Objects ');
}

The DescribeSObjectResult Class contains methods for describing sObjects.

Important Methods for DescribeSObjectResult. All are instance methods.
fields
Follow fields with a field member variable name or with the getMap method.

getChildRelationships()
Returns a list of child relationships, which are the names of the sObjects that have a foreign key to the sObject being described.

getLabel()
Returns the object’s label, which may or may not match the object name.

getLabelPlural()
Returns the object’s plural label, which may or may not match the object name.

getName()
Returns the name of the object.

getSobjectType()
Returns the Schema.SObjectType object for the sObject. You can use this to create a similar sObject.

isAccessible()
Returns true if the current user can see this object, false otherwise.

isCreateable()
Returns true if the object can be created by the current user, false otherwise.

isCustom()
Returns true if the object is a custom object, false if it is a standard object.

isCustomSetting()
Returns true if the object is a custom setting, false otherwise.

isDeletable()
Returns true if the object can be deleted by the current user, false otherwise.

isQueryable()
Returns true if the object can be queried by the current user, false otherwise

isSearchable()
Returns true if the object can be searched by the current user, false otherwise.

isUndeletable()
Returns true if the object cannot be undeleted by the current user, false otherwise.

isUpdateable()
Returns true if the object can be updated by the current user, false otherwise.