Dynamic Apex in Salesforce

Dynamic Apex in Salesforce helps developers to build flexible applications by catering 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 re-used 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 an 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

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. 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 an 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 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

To get the metadata of a field using DescribeFieldResult

To Describe sObject using Schema method

Learn more

Dynamic SOQL

Dynamic SOSL

Dynamic DML

Ravi Teja
Ravi Teja

Salesforce Consultant at Global Consulting Firm
12x Salesforce Certified Application Architect

Articles: 9

2 Comments

  1. sObjectType.Contact would give you a DescribeSobjectResult. Schema.getGlobalDescribe is more efficient than describing on a list of subject names

Leave a Reply

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