Tuesday, September 13, 2016

Dynamic Apex in Salesforce

You can fetch all sobject and their field information in apex by using describe methods. Apex gives 2 data types for sobject and field information.
  1. Token: A lightweight, serializable reference to an sObject or a field that is validated at compile time.
  2. Describe Result: It contains all the describe information about sobject and fields. Describe result objects are not serializable, and are validated at runtime.
It is easy to move from a token to its describe result, and vice versa. Both sObject and field tokens have the method getDescribe which returns the describe result for that token.
On the describe result, the getSObjectType and getSObjectField methods return the tokens for sObject and field, respectively.

Finding All object in Organization

Schema getGlobalDescribe method returns a map that represents the relationship between all sObject names (keys) to sObject tokens (values).
For example:
Map<String, Schema.SObjectType> schemaMapOfOrg = Schema.getGlobalDescribe();
The map has the following characteristics:
  • It is dynamic, that is, it is generated at runtime on the sObjects currently available for the organization, based on permissions.
  • The sObject names are case insensitive. 
  • The keys use namespaces as required. The keys reflect whether the sObject is a custom object.
Creating sObjects Dynamically

If we need to create contact record dynamically, then use below code:
String typeName='Contact';
Schema.SObjectType objToken = Schema.getGlobalDescribe().get(typeName);
sobject son= objToken.newSObject();
insert son;

Apex code to find all sobject and their fields

Apex code to generate SOQL to fetch all fields of an object

Monday, September 12, 2016

RecordTypeId using Describe & SOQL

RecordTypeId of an object can be determined by using 2 different options:

For example we will find out the recordtypeId of "Renewal" recordtype of opportunity.

By Using Describe:
Id renewalRecordTypeId = Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get('Renewal').getRecordTypeId();
Advantage: Saves on SOQL limits but uses a describe call.

By using SOQL:
Id renewalRecordTypeId =[select id from recordType where  sobjectType='Opportunity' AND DeveloperName='Renewal'].Id;
Advantage of SOQL: If in future, someone change the name of recordtype, the code will work as it refers developername.