Get sObject Field Value Dynamically With Apex

Sept 15, 2023


 

 

After completing this unit, you will able to:

1. Introduction
2. Dynamic Object Retrieval
3. Dynamic Field Access
4. Dynamic Queries

Introduction

"Dynamically getting" in Apex refers to the process of accessing or retrieving data, objects, or fields at runtime based on conditions or variables rather than hardcoding them into your code. This dynamic approach is useful when you don't know the exact data or metadata you need until your code is executing. Here are a few scenarios where dynamic access is valuable:

Dynamic Object Retrieval: When you need to work with different SObjects (database tables) based on user input or configuration, you can dynamically fetch the object's metadata and create or query records.

 

Apex Code:

Id recordId = '0015i00000B6LivAAF';
SObjectType objectType = recordId.getSObjectType();
system.debug(objectType);

 

Dynamic Record Creation And Field Access: If you want to access fields on SObjects, but you don't know the field names until runtime (e.g., based on user input or customization), you can use dynamic field access to fetch, update, or manipulate field values.

 

Apex Code:

Schema.SObjectType tt = Schema.getGlobalDescribe().get('Account');
SObject so = tt.newSObject();
so.put('Name','test1');
insert so;
String accountName = (String)so.get('Name');
system.Assert(false, 'accountName = ' +accountName);

 

Dynamic Queries:

In this case, you dynamically build the SOQL query string based on the object, field, and search criteria, and then execute the query using Database.query().

 

Apex Code:

Id recordId = '0015i00000B6LivAAF';
SObjectType objectType = recordId.getSObjectType();
Map<String, SObjectField> fieldMap = objectType.getDescribe().fields.getMap();
String dynamicQuery = 'SELECT ';
for (String fieldName : fieldMap.keySet()) {
dynamicQuery += fieldName + ', ';
}
dynamicQuery = dynamicQuery.removeEnd(', ') + ' FROM ' + objectType + ' WHERE Id = :recordId LIMIT 1';
SObject obj = Database.query(dynamicQuery);
if (obj != null) {
String fieldValue1 = (String)obj.get('Name');
String fieldValue2 = (String)obj.get('Rating');
System.debug(' ObjectName = ' + objectType);
System.debug(' Name = ' + fieldValue1);
System.debug(' Rating = ' + fieldValue2);
}
else {
}

 

 

I hope this blog helped you!