Dynamic Apex in Salesforce Explained.
1. What is Dynamic Apex in Salesforce?
Dynamic Apex allows users to execute Dynamic queries using Dynamic SOQL and SOSL and also helps in the creation of sObjects dynamically.
Dynamic Apex enables developers to:
- Access object information and fields metadata. The metadata here does not only comprise the API name, but information about the editability of the field, the field length, is the field a compound field or not, relationship between objects and picklist values available.
- It contains information about the salesforce apps comprising the tabs available.
Isn’t that an amazing feature to have access to all the details at one place on the fly.
Now, to access information related to the object, there is a class called the Schema in apex. It includes various functions. Some of its widely used functions are:
describeglobal() | Describes the list of all the objects in the org. |
describeSObject() | Retrieves metadata about an individual object. |
getGlobalDescribe() | Returns a map of all the object names and tokens for standard and custom objects. |
getDescribe() | Retrieves metadata about an individual field. |
getRecordTypeInfos() | Retrieves a list of record types supported by an object. |
getChildRelationships() | Retrieves a list of child relationships for the subject being described. |
getPicklistValues() | Retrieves picklist values. |
getName() | Retrieve the field name. |
getLabel() | Retrieve field label. |
2. Dynamic Apex Common Use Cases
Let’s go over some of the most common Dynamic Apex use cases in Salesforce.
2.1 Find Parent Relationship of an Object
There is a predefined function called childRelationship which can be used to fetch the objects which lie below the queried object in the Hierarchy. But, in order to extract the parent relationships, we need to follow a different route. Let’s see how this works!
Code:
The Line 1 in the above code fetches the metadata of the object, which in this case is account. It contains details regarding the fields,record types and many more. We move on to get the field information in Line 2. It is stored as a map with the API name of the field stored as a key value and the field’s metadata as a value with Schema.SobjectField type.
Moving forward, an iterator is used which checks the field metadata for each field.
The differentiating factor for a field which is a child and has a parent object is that itsthat, its referenceTo tag in the metadata is not null but points to the parent object.
The result we get while debugging is shown below:
2.2 Get Picklist Values for a Field
Here, we are fetching the picklist values for the field Stage in Opportunity Object. Line 1 contains the metadata of the object. Moving forward, a key value pair is created with the field name as key and its metadata as value. The metadata of the field is fetched using the getDescribe() method. PicklistEntry is a predefined return type which can store all the details for picklist fields. A for loop is then run, and each picklist value is iterated and shown as output.
The output here contains all the tags for a picklist field. Individual components can be queried according to the needs.
2.3 Fetch Field Metadata
To get field metadata, we first need to locate the object details. There are two ways of getting the object metadata.
- Specify the name of the object as illustrated in the previous examples.
2. Specify the name of the object on the fly as shown in the example coming up next.
Here, getGlobalDescribe() contains the details of all the objects . Then, as shown in Line 2 we can specify the name of the object and get the metadata.
Fields.size() in line 5 is used to fetch the number of fields an object contains.
2.4 Get Record Type Details
In order to get all the information concerning Record Types consolidated in one place,
The isAvailable() method is used to check if the Record Type is available for use to the Logged in User. Salesforce has a method called Schema.RecordTypeInfo as illustrated in the Code Above.
Important Note: The Schema in Schema.SObjectType and Schema.DescribeSObjectResult is a namespace whereas, the Schema in Schema.getGlobalDescribe() is a class. Please don’t get confused between the two.
2.5 Dynamic DML
Apart from executing queries on the fly, we can also create sObjects during run time.
A new SObject can be created using newSObject method .We need to explicitly typecast the newly created sObject,failing to do so would throw an error as can be seen below.
The error can be rectified by type casting the token with the sObject type as shown in the below code.
The following code also illustrates ways to specify the field values while creating a record.
Record Created in Salesforce:
3. Final Thoughts
Using Dynamic Apex provides a chance to check field/ Object level permissions at runtime. Dynamic very handy for creating sObject and executing Queries in the runtime. The Dynamic SOQL and SOSL have the same governor limits as static SOQL and SOSL respectively. To read further about governor limits, please refer this article.
The Playground is open to play with Dynamic Apex. Please go ahead and use the code snippets provided in this article to get started on your journey to mastering Dynamic Apex.
4. Additional Resources
Written By…
Riya is headed to pursue MBA from XLRI Jamshedpur’25. She is 5x certified Salesforce Admin, Developer and consultant. When she is not juggling with the hectic life in a B-school, you can find her blazing trails on trailhead, reading books, painting, swimming or sharing her experiences through a blog.
Disclaimer: The views and opinions expressed in this article are solely those of the author and do not reflect the views of DineshYadav.com. DineshYadav.com does not endorse any of the third party organizations or applications mentioned in the article, including their legality, integrity, quality, accuracy or any applicable intellectual property rights.
Other Articles by Riya Sawa…
Thanks for sharing a clear explanation of how to use dynamic apex in salesforce. It is one of the important topic in salesforce everyone should know about this.
Just needed one clarification here – In the section 5 (Dynamic DML), why the phone number for that new contact has been added with two liner code. It can simply be
b.put(‘Phone’, ‘12345’);
What is the advantage/ significance of using DescribeFieldResult to retrieve the details of “Phone” field and then apply “getObjectField()” method to return the Schema.SObjectField token for that field to populate a value?