Hello friends, today we will discuss Set and Get Sobject fields dynamically in Apex. In Apex, Salesforce’s programming language, it is often necessary to dynamically set or retrieve the values of fields on an SObject. This can be useful when working with generic or reusable code, or when the fields you need to access are not known until runtime.
Also, check this: SALESFORCE SPRING ’23 RELEASE HIGHLIGHTS
Key Highlights :
- To set the value of a field on an SObject dynamically, you can use the
put
method on theSObject
class. - The
put
method takes two arguments: the field name, and the value you want to set. - To retrieve the value of a field on an SObject dynamically, you can use the
get
method on theSObject
class. - The
get
method takes one argument: the field name. - These methods can be very useful when working with Apex, especially when working with generic or reusable code, or when the fields you need to access are not known until runtime.
Code :
Example of how you might use the put method : This code creates a new Account object, and sets the value of its Name field to ‘My Account’.
Account a = new Account(); a.put('Name', 'My Account');
Example of how you might use the get method : This code creates a new Account object, sets the value of its Name field to ‘My Account’, and retrieves the value of the Name field and store it in a variable named accountName.
Account a = new Account(); a.put('Name', 'My Account'); String accountName = (String)a.get('Name');