Set and Get Sobject fields dynamically in Apex

by Rijwan Mohmmed
0 comment
set-and-get-sobject-fields-dynamically-in-apex-salesforce-techdicer

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 :

  1. To set the value of a field on an SObject dynamically, you can use the put method on the SObject class.
  2. The put method takes two arguments: the field name, and the value you want to set.
  3. To retrieve the value of a field on an SObject dynamically, you can use the get method on the SObject class.
  4. The get method takes one argument: the field name.
  5. 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');

Output :

Reference :

  1. Apex
What’s your Reaction?
+1
7
+1
1
+1
2
+1
1
+1
1
+1
2

You may also like

Leave a Comment

* By using this form you agree with the storage and handling of your data by this website.