Introduction
Salesforce provides sObject methods and all of these methods are instance methods such as addError(), get(), etc. This article explains one of the real-time usages of the put() method. It can reduce code and make the code efficient instead of hard coding Field or Object Names. Recently we had a scenario like field names should be assigned dynamically.
Consider the below two objects,
- Opportunity (Standard Object)
- OpportunityStatusHistory__c (Custom Object)
Problem
The OpportunityStatusHistory__c custom object fields are named like Prospecting__c, Qualification__c, etc. The field names are equal to the Stage Name’s in Opportunity object.
Whenever a new Opportunity record is created or updated with a particular stage, then we need to count the stage history details in “OpportunityStatusHistory” object. For example, if we create an opportunity with Stage “Prospecting”, then OpportunityStatusHistory object record should be created with the corresponding Prospecting__c field value set as 1.
If we changed the above opportunity stage to “Qualification”, then corresponding OpportunityStatusHistory object field Qualification__c value to be set as 1. If I go to backward stage i.e. “Prospecting”, then related Prospecting__c field in OpportunityStatusHistory record should get updated as 2.
Example Code Snippet:
In the below code snippet, I am checking the Opportunity stage field values and assigning the value to the related OpportunityStatusHistory object fields. Suppose if I have 100 stages, then code become complex.
- for(Opportunity currentOpp : Trigger.New)
- {
- OpportunityStatusHistory__c statusHistory = new OpportunityStatusHistory__c();
- If(currentOpp.StageName == ‘Prospecting’)
- {
- statusHistory.Prospecting__c = ‘1’;
- }
- else if(currentOpp.StageName == ‘Qualification’)
- {
- statusHistory.Qualification__c = ‘1’;
- }
- }
Solution
To overcome this we can utilize the Dynamic Apex. It can help you to write flexible code.
- Map<String, String> opportunityStatusFieldMap = new Map<String, String>();
- Map<String, Schema.SObjectField> opportunityStatusDescribe = OpportunityStatusHistory__c.sObjectType.getDescribe().fields.getMap();
- for(Schema.SObjectField currentField : opportunityStatusDescribe.Values())
- {
- Schema.DescribeFieldResult fieldResult = currentField.getDescribe();
- opportunityStatusFieldMap.put(fieldResult.getLabel(), fieldResult.getName());
- }
- for(Opportunity currentOpp : Trigger.New)
- {
- OpportunityStatusHistory__c statusHistory = new OpportunityStatusHistory__c();
- statusHistory.put(opportunityStatusFieldMap.get(currentOpp.Stage__c), 1); // This put method used to dynamically assign field values
- }
Conclusion
This approach is efficient and easier to use than checking conditions every time and assigning to the corresponding fields, and we can easily get and assign the field values dynamically at run time.
Reference: