Tuesday, March 12, 2019

Efficient way of dynamically casting SObject to Specific Object to update records

Use Case


Developer has a requirement to typecast specific object type from the name of SObject and try to update record of the SObject.

For example, SObject name is "Account" and Id is ''0012v00002AyZWE''.

Developer wants to update Account Name or other field values.



Solution


Create an instance of SObject based on reflection as follows:

  1. String sObjectName = 'Account';  
  2.   
  3. SObject actObj = (SObject)(Type.forName('Schema.'+ sObjectName).newInstance());  


We can also create an instance of SObject based on global describe as follows:

  1. String sObjectName = 'Account';  
  2.   
  3. SObject sObj = Schema.getGlobalDescribe().get(sObjectName).newSObject(); 

But, first one is most efficient which executes in 1ms where as second one takes 75ms and may be higher based on number of objects available at our Salesforce org.

So, lets put the desired solution:

  1. String sObjectName = 'Account';  
  2. String recordId = '0012v00002AyZWE';  
  3.   
  4. SObject actObj = (SObject)(Type.forName('Schema.'+ sObjectName).newInstance());  
  5. actObj.Id = recordId;  
  6. actObj.put('Name''New Account2');  
  7. update actObj; 

 We can easily put that in the list of SObject and update the records in one single goal.

If we have Id of a record then we can create an instance of SObject as follows:

  1. Id sampleid = '0012v00002AyZWE';  
  2. SObject actObj = sampleid.getSObjectType().newSObject();  


So, the entire solution approach will be as follows:

  1. Id sampleid = '0012v00002AyZWE';  
  2. SObject actObj = sampleid.getSObjectType().newSObject();  
  3. actObj.Id = recordId;  
  4. actObj.put('Name''New Account3');  
  5. update actObj; 

Conclusion


From the above approaches which one needs to be followed that truly depends on individual use cases. It's good that Apex provides different ways to typecast SObject to specific object.

1 comment:

  1. The article was up to the point and described the information very effectively. Thanks to blog author for wonderful and informative post.
    Security Service

    ReplyDelete