[SalesForce] Generic SObject update pattern

Question

I know that it is possible to update a generic of List<SObject>, But what is the best approach to generate that list without knowing the SObjectType, only the ids ?

Sample:

 List<SObject> l = new List<SObject>();
 
 SObject o1 = new SObject(id='xxxxxx'); //this Id could be an Account
 o1.Name = 'Test';
 l.add(o1);


 SObject o2 = new SObject(id='xxxxxx'); //this Id could be a Custom
 o2.Name = 'Test' 
 l.add(o2); 
 
 //this is possible
 update l;

Unfortunately, SObject constructor doesn't allow id as parameter.

Backgound:

I'm trying to make a generic WS which will receive a list of objects to update( or upsert). The received object could by any type.

WS Request sample:

  [
   {id:'xxxxx',Name:'Test'},
   {id:'yyyyy',Name:'Test 2'},
   {id:'zzzzz',Name:'Test 3'}
  ]

The id attribute cloud be from any SObject.( I know the extra attr to update always exist).

Thanks in advance for your time.

Best Answer

Once you have the sObjectType you should be able to construct the sObject instance using the sObjectType.newSObject(ID Id) method. You can get the sObjectType from the Id using the Id.getSObjectType() method;

Map<Id, String> idsToUpdate = new Map<Id, String>();

// Put the Id's and associated name values in the map

List<SObject> sObjectsToUpdate = new List<SObject>();

for (Id idToUpdate : idsToUpdate.keySet()) {
    SObject o1 = idToUpdate.getSObjectType().newSObject(idToUpdate);
    // Set the Name field dynamically
    o1.put('Name', idsToUpdate.get(idToUpdate));
    sObjectsToUpdate.add(o1);
}

update sObjectsToUpdate;
Related Topic