Generic SObject update pattern
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;
Here's a link to a post that I think answers your question: Infering sObject Type from Id
or collection of Id
's
Essentially, the solution entails:
- Pulling the sObject "prefix" (the first 3 characters) from the
id
you receive - Get the
sObjectType
so you can cast your objects as the correspondingsObject
(orlist<yourSobject__c>
) - Upsert the typed-records
Link to SF Docs
Here's a Utility Method I wrote that writes a query to select ALL fields from an sObject by only giving the string value of the Object Name
. It exemplifies finding an sObject's metadata (in this case, its fields
).
public static string FormatFieldsForQuery(string objectName,string prefix){
if(string.isNotBlank(prefix)){
if(prefix.endsWith('__c'))
prefix=prefix.replace('__c','__r.');
if(!prefix.endsWith('.'))
prefix+='.';
}
string fields = '';
sObjectType objectType=Schema.getGlobalDescribe().get(objectName);
if(objectType==null)
return fields;
for(string f :objectType.getDescribe().fields.getMap().keySet())
fields+=prefix+f+',';
return fields.removeEnd(',');
}//END FormatFieldsForQuery(string objectName,string prefix)