Dynamic Apex in Salesforce helps developers build flexible applications by catering to them with the below features.
What is Dynamic Apex in Salesforce?
Dynamic Apex helped developers to create flexible applications. With dynamic apex in Salesforce, we can write Generic Code that can be reused again with multiple sObjects. So, the logic that you’ve written is not object-dependent. You can make your SOQL queries, SOSL queries, and DML statements dynamic. Let’s have a look at some good use cases to see how to use them.
Access sObject and field describe information
To know the metadata information about a sObject like sObject’s name, type & label, fields and child objects. This is also known as Schema Programming. To know the describe information of a field like field length, type etc.
Access Salesforce App Information
To know the describe information for standard and custom apps available in Salesforce. Provides metadata information related to label, tabs etc.
Dynamic SOQL, SOSL and DML
In Salesforce dynamic SOQL refers to the generation of a SOQL string at run time with Apex. Similarly SOSL refers to the generation of a SOSL string at run time with Apex.
To execute SOQL or SOSL as a string at runtime. Based on User Input, queries are built and executed as a string with predefined database methods. With dynamic DML provides the potential to create a record dynamically and insert it into the database using DML.
Apex Describe Information
Describe sObjects either by using tokens or the describeSObjects Schema method.
- Token – a reference to a sObject or a field that is validated at compile time.
- DescribeSObjects method – a method in the Schema class that implements describes on one or more sObject types.
- Describe the result – an object of type Schema.DescribeSObjectResult that holds all the describe properties for the sObject or a field. When implementing the describe using either the sObject token or the describeSObjects method, the result object is returned.
Learn more here.
Token for the Contact Object
To get the sObject Describe Results using Tokens
Use DescribeFieldResult To get the metadata of a field.
To Describe sObject using Schema method
Learn more
- https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_dynamic_describeSObject.htm
- https://developer.salesforce.com/docs/atlas.en-us.244.0.apexref.meta/apexref/apex_methods_system_sobject_describe.htm
sObjectType.Contact would give you a DescribeSobjectResult. Schema.getGlobalDescribe is more efficient than describing on a list of subject names
Thanks for sharing